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): consolidate account modules and shared errors (#42570)
Byron.wang95373bc4fdc2
diff --git a/api/.importlinter b/api/.importlinterindex 1939f41a963..207c7f8340a 100644--- a/api/.importlinter+++ b/api/.importlinter@@ -61,7 +61,6 @@ ignore_imports =core.app.features.annotation_reply.annotation_reply -> services.annotation_servicecore.app.features.annotation_reply.annotation_reply -> services.knowledge.dataset_servicecore.app.llm.quota -> services.credit_pool_service- core.app.task_pipeline.message_cycle_manager -> services.account_servicecore.app.task_pipeline.message_cycle_manager -> services.annotation_servicecore.app.workflow.layers.persistence -> services.workflow.inspector_eventscore.helper.credential_utils -> services.enterprise.plugin_manager_service@@ -72,9 +71,7 @@ ignore_imports =core.rag.datasource.retrieval_service -> services.knowledge.external.servicecore.rag.index_processor.index_processor -> services.vector_space_admission_servicecore.rag.index_processor.index_processor_base -> services.file_service- core.rag.index_processor.processor.paragraph_index_processor -> services.account_servicecore.rag.index_processor.processor.paragraph_index_processor -> services.knowledge.summaries.adapters- core.rag.index_processor.processor.parent_child_index_processor -> services.account_servicecore.rag.index_processor.processor.parent_child_index_processor -> services.knowledge.summaries.adapterscore.rag.index_processor.processor.qa_index_processor -> services.knowledge.summaries.adapterscore.rag.retrieval.dataset_retrieval -> services.knowledge.external.service@@ -115,8 +112,6 @@ ignore_imports =libs.oauth_bearer -> modelslibs.rsa -> extensions.ext_storagelibs.workspace_permission -> services.enterprise.enterprise_service- services.account_service -> controllers- services.account_service -> controllers.console.errorservices.app_generate_service -> controllers.console.app.workflow[importlinter:contract:no-direct-rsa-imports]@@ -156,16 +151,22 @@ forbidden_modules =werkzeug[importlinter:contract:workspace-query-service-boundary]-name = Workspace query application service is framework and persistence neutral+name = Workspace application services and contracts are framework and persistence neutraltype = forbiddensource_modules =- services.workspace_query_service+ services.workspace.service+ services.workspace.provisioning_service+ services.workspace.contractsforbidden_modules =+ configscontrollersextensionsflaskmodelsrepositories+ services.billing_service+ services.feature_service+ services.workspace.gatewayssqlalchemywerkzeug@@ -431,16 +432,16 @@ source_modules =services.account_avatar_serviceservices.account_change_email_portsservices.account_change_email_service- services.account_email_registration_service+ services.account.email_registration_serviceservices.account_deletion_serviceservices.account_deletion_feedback_serviceservices.account_education_serviceservices.account_errors- services.account_forgot_password_service+ services.account.forgot_password_serviceservices.account_initialization_serviceservices.account_integration_service- services.account_login_service- services.account_oauth_service+ services.account.login_service+ services.account.oauth_serviceservices.account_password_serviceservices.account_portsservices.account_profile_service@@ -696,7 +697,7 @@ forbidden_modules =name = Workspace member query application service is framework and persistence neutraltype = forbiddensource_modules =- services.workspace_member_query_service+ services.workspace.member_serviceforbidden_modules =configscontrollers@@ -705,7 +706,7 @@ forbidden_modules =modelsrepositoriesservices.enterprise- services.workspace_member_role_resolver+ services.workspace.gatewayssqlalchemywerkzeug@@ -1060,3 +1061,20 @@ forbidden_modules =services.audio_servicesqlalchemywerkzeug++[importlinter:contract:account-lifecycle-boundary]+name = Account lifecycle use cases and contracts are framework and persistence neutral+type = forbidden+source_modules =+ services.account.service+ services.account.contracts+forbidden_modules =+ configs+ controllers+ extensions+ flask+ models+ repositories+ services.account.adapters+ sqlalchemy+ werkzeugdiff --git a/api/commands/account.py b/api/commands/account.pyindex dc00f431a77..8cadff1f040 100644--- a/api/commands/account.py+++ b/api/commands/account.py@@ -1,15 +1,11 @@-import base64import secretsimport click-from sqlalchemy.orm import Sessionfrom constants.languages import languages-from extensions.ext_database import db+from extensions.ext_application_services import application_servicesfrom libs.helper import email as email_validate-from libs.password import hash_password, password_pattern, valid_password-from services.account_email import normalize_email-from services.account_service import AccountService, RegisterService, TenantService+from libs.password import password_pattern, valid_password@click.command("reset-password", help="Reset the account password.")@@ -26,7 +22,7 @@ def reset_password(email, new_password, password_confirm):returnnormalized_email = email.strip().lower()- account = AccountService.get_account_by_email_with_case_fallback(email.strip(), session=db.session())+ account = application_services().accounts.lifecycle.get_account_by_email_with_case_fallback(email.strip())if not account:click.echo(click.style(f"Account not found for email: {email}", fg="red"))@@ -38,19 +34,7 @@ def reset_password(email, new_password, password_confirm):click.echo(click.style(f"Invalid password. Must match {password_pattern}", fg="red"))return- # generate password salt- salt = secrets.token_bytes(16)- base64_salt = base64.b64encode(salt).decode()-- # encrypt password with salt- password_hashed = hash_password(new_password, salt)- base64_password_hashed = base64.b64encode(password_hashed).decode()- with Session(db.engine) as session:- account = session.merge(account)- account.password = base64_password_hashed- account.password_salt = base64_salt- session.commit()- AccountService.reset_login_error_rate_limit(normalized_email)+ application_services().accounts.lifecycle.reset_password(account.id, new_password, email=normalized_email)click.echo(click.style("Password reset successfully.", fg="green"))@@ -68,7 +52,7 @@ def reset_email(email, new_email, email_confirm):returnnormalized_new_email = new_email.strip().lower()- account = AccountService.get_account_by_email_with_case_fallback(email.strip(), session=db.session())+ account = application_services().accounts.lifecycle.get_account_by_email_with_case_fallback(email.strip())if not account:click.echo(click.style(f"Account not found for email: {email}", fg="red"))@@ -80,11 +64,7 @@ def reset_email(email, new_email, email_confirm):click.echo(click.style(f"Invalid email: {new_email}", fg="red"))return- with Session(db.engine) as session:- account = session.merge(account)- account.email = normalized_new_email- account.normalized_email = normalize_email(normalized_new_email)- session.commit()+ application_services().accounts.lifecycle.set_email(account.id, normalized_new_email)click.echo(click.style("Email updated successfully.", fg="green"))@@ -129,15 +109,14 @@ def create_tenant(email: str, language: str | None = None, name: str | None = Noreturn# register account- account = RegisterService.register(+ account = application_services().accounts.lifecycle.register(email=email,name=account_name,password=new_password,language=language,create_workspace_required=False,- session=db.session(),)- TenantService.create_owner_tenant_if_not_exist(account, name, session=db.session())+ application_services().workspaces.provisioning.create_owner_workspace(account.id, name=name, if_missing=True)click.echo(click.style(diff --git a/api/controllers/common/errors.py b/api/controllers/common/errors.pyindex c865e5eceb4..78cee1b813c 100644--- a/api/controllers/common/errors.py+++ b/api/controllers/common/errors.py@@ -1,4 +1,12 @@+from collections import OrderedDict+from http import HTTPStatus+from typing import cast++from flask import current_app, got_request_exception+from flask_restx import Api+from libs.exception import BaseHTTPException+from services.errors.base import NoPermissionErrorclass FilenameNotExistsError(BaseHTTPException):@@ -87,3 +95,19 @@ class NotFoundError(BaseHTTPException):class InvalidArgumentError(BaseHTTPException):error_code = "invalid_param"code = 400+++def register_permission_error_handler(api: Api) -> None:+ """Preserve the default permission-error response for Console and Service API."""++ @api.errorhandler(NoPermissionError)+ def handle_permission_error(error: NoPermissionError) -> tuple[dict[str, str | int], int]:+ got_request_exception.send(current_app, exception=error)+ return {+ "code": InvalidArgumentError.error_code,+ "message": str(error),+ "status": HTTPStatus.BAD_REQUEST,+ }, HTTPStatus.BAD_REQUEST++ # Flask-RESTX picks the first matching handler, including the generic Exception handler.+ cast(OrderedDict[type[Exception], object], api.error_handlers).move_to_end(NoPermissionError, last=False)diff --git a/api/controllers/console/__init__.py b/api/controllers/console/__init__.pyindex ca37bd6bce9..a40044be719 100644--- a/api/controllers/console/__init__.py+++ b/api/controllers/console/__init__.py@@ -6,6 +6,7 @@ from typing import castfrom flask import Blueprint, current_app, got_request_exceptionfrom flask_restx import Namespace+from controllers.common.errors import register_permission_error_handlerfrom libs.external_api import ExternalApifrom machinery.errors import ActiveWorkspaceRequiredError@@ -17,6 +18,7 @@ api = ExternalApi(title="Console API",description="Console management APIs for app configuration, monitoring, and administration",)+register_permission_error_handler(api)@api.errorhandler(ActiveWorkspaceRequiredError)diff --git a/api/controllers/console/apikey.py b/api/controllers/console/apikey.pyindex 2b833bfb2a1..8e157dbfff9 100644--- a/api/controllers/console/apikey.py+++ b/api/controllers/console/apikey.py@@ -24,7 +24,7 @@ from services.auth.api_key_contracts import (ApiKeyNotFoundError,ApiKeyResourceNotFoundError,)-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.knowledge.api_key_service import UnknownDatasetIdsErrorAPI_KEY_EDIT_ROLES = frozenset({TenantAccountRole.OWNER, TenantAccountRole.ADMIN, TenantAccountRole.EDITOR})diff --git a/api/controllers/console/app/app.py b/api/controllers/console/app/app.pyindex e1db9164dca..8df3ba9e3d7 100644--- a/api/controllers/console/app/app.py+++ b/api/controllers/console/app/app.py@@ -79,7 +79,7 @@ from services.entities.app_entities import (UpdateAppParams,)from services.entities.dsl_entities import ImportStatus-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.knowledge.entities.knowledge_entities import (DataSource,InfoList,diff --git a/api/controllers/console/app/app_import.py b/api/controllers/console/app/app_import.pyindex 959d0e7f47c..78cb85c5470 100644--- a/api/controllers/console/app/app_import.py+++ b/api/controllers/console/app/app_import.py@@ -17,7 +17,7 @@ from models.account import TenantAccountRolefrom services.agent.errors import InvalidRosterAgentPackageErrorfrom services.app.console_service import ConsoleAppNotFoundErrorfrom services.entities.dsl_entities import AppImportParams, CheckDependenciesResult, Import, ImportStatus-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.recommended_app_query_service import RecommendedAppNotFoundErrorfrom .. import console_nsdiff --git a/api/controllers/console/app/workflow_comment.py b/api/controllers/console/app/workflow_comment.pyindex 112443321ee..c70c44fd4f4 100644--- a/api/controllers/console/app/workflow_comment.py+++ b/api/controllers/console/app/workflow_comment.py@@ -16,6 +16,7 @@ from controllers.console.wraps import (with_current_tenant_id,with_current_user,)+from extensions.ext_application_services import application_servicesfrom extensions.ext_database import dbfrom fields.base import ResponseModelfrom fields.member_fields import AccountWithRole@@ -31,7 +32,6 @@ from models.comment import (from models.comment import (WorkflowCommentReply as WorkflowCommentReplyModel,)-from services.account_service import TenantServicefrom services.workflow_comment_service import WorkflowCommentServicelogger = logging.getLogger(__name__)@@ -585,7 +585,7 @@ class WorkflowCommentMentionUsersApi(Resource):current_tenant = current_user.current_tenant # need the tenant object hereif current_tenant is None:raise ValueError("current tenant is required")- members = TenantService.get_tenant_members(current_tenant, session=db.session())+ members = application_services().workspaces.member_queries.list_members(current_tenant.id)users = TypeAdapter(list[AccountWithRole]).validate_python(members, from_attributes=True)response = WorkflowCommentMentionUsersPayload(users=users)return response.model_dump(mode="json"), 200diff --git a/api/controllers/console/auth/activate.py b/api/controllers/console/auth/activate.pyindex adf88afc1da..2d4dd10907b 100644--- a/api/controllers/console/auth/activate.py+++ b/api/controllers/console/auth/activate.py@@ -12,14 +12,8 @@ from extensions.ext_application_services import application_servicesfrom libs.helper import EmailStr, dump_response, timezonefrom libs.login import current_account_with_tenantfrom libs.token import extract_access_token-from services.account_activation_service import (- EmailDomainSuspendedError as EmailDomainSuspendedRegistrationError,-)-from services.account_activation_service import (- FrozenAccountError,- InvalidInvitationError,- InvitationAccountMismatchError,-)+from services.account_errors import AccountEmailDomainSuspendedError as EmailDomainSuspendedRegistrationError+from services.account_errors import FrozenAccountError, InvalidInvitationError, InvitationAccountMismatchErrorfrom services.entities.account_activation_entities import ActivationCommand, InvitationLookup@@ -91,7 +85,7 @@ class ActivateCheckApi(Resource):)@model_validate(ActivateCheckQuery)def get(self, args: ActivateCheckQuery):- result = application_services().account_activation.check(+ result = application_services().accounts.activation.check(InvitationLookup(workspace_id=args.workspace_id,email=args.email,@@ -128,7 +122,7 @@ class ActivateApi(Resource):authenticated_account_id = current_account_with_tenant().account.idtry:- application_services().account_activation.activate(+ application_services().accounts.activation.activate(ActivationCommand(invitation=InvitationLookup(workspace_id=args.workspace_id,diff --git a/api/controllers/console/auth/email_register.py b/api/controllers/console/auth/email_register.pyindex e0bfddccfa0..ec1d1e94606 100644--- a/api/controllers/console/auth/email_register.py+++ b/api/controllers/console/auth/email_register.py@@ -154,7 +154,7 @@ class EmailRegisterResetApi(Resource):@model_validate(EmailRegisterResetPayload)def post(self, args: EmailRegisterResetPayload):try:- token_pair = application_services().accounts.email_registration.register(+ tokens = application_services().accounts.email_registration.register(remote_ip=extract_remote_ip(request),token=args.token,new_password=args.new_password,@@ -179,5 +179,5 @@ class EmailRegisterResetApi(Resource):return dump_response(EmailRegisterResetResponse,- {"result": "success", "data": token_pair},+ {"result": "success", "data": tokens},)diff --git a/api/controllers/console/auth/login.py b/api/controllers/console/auth/login.pyindex e17325cc269..e08b27beb09 100644--- a/api/controllers/console/auth/login.py+++ b/api/controllers/console/auth/login.py@@ -60,12 +60,8 @@ from libs.token import (set_refresh_token_to_cookie,)from services import account_errors-from services.entities.account_login_entities import (- AuthTokenPair,- EmailCodeLoginCommand,- EmailCodeSendCommand,- PasswordLoginCommand,-)+from services.entities.account_entities import AccountSessionTokens+from services.entities.account_login_entities import EmailCodeLoginCommand, EmailCodeSendCommand, PasswordLoginCommandfrom services.entities.auth_entities import LoginPayloadBase@@ -141,7 +137,7 @@ class LoginApi(Resource):except account_errors.AccountApplicationError as error:_raise_request_error(error)- if not result.workspace_found or result.token_pair is None:+ if not result.workspace_found or result.tokens is None:return dump_response(SimpleResultOptionalDataResponse,{@@ -149,7 +145,7 @@ class LoginApi(Resource):"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"})+ return _token_response(result.tokens, SimpleResultOptionalDataResponse, {"result": "success"})@console_ns.route("/logout")@@ -218,7 +214,7 @@ class EmailCodeLoginApi(Resource):@model_validate(EmailCodeLoginPayload)def post(self, req_data: EmailCodeLoginPayload):try:- token_pair = application_services().accounts.authentication.login_with_email_code(+ tokens = application_services().accounts.authentication.login_with_email_code(EmailCodeLoginCommand(email=req_data.email,code=req_data.code,@@ -231,7 +227,7 @@ class EmailCodeLoginApi(Resource):)except account_errors.AccountApplicationError as error:_raise_request_error(error)- return _token_response(token_pair, SimpleResultResponse, {"result": "success"})+ return _token_response(tokens, SimpleResultResponse, {"result": "success"})@console_ns.route("/refresh-token")@@ -247,21 +243,21 @@ class RefreshTokenApi(Resource):), HTTPStatus.UNAUTHORIZEDtry:- token_pair = application_services().accounts.authentication.refresh(refresh_token)+ tokens = 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"})+ return _token_response(tokens, SimpleResultResponse, {"result": "success"})-def _token_response(token_pair: AuthTokenPair, response_model: type[BaseModel], data: object):+def _token_response(tokens: AccountSessionTokens, response_model: type[BaseModel], data: object):# response-contract:ignore cookie-bearing Flask responseresponse = 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)+ set_csrf_token_to_cookie(request, response, tokens.csrf_token)+ set_access_token_to_cookie(request, response, tokens.access_token)+ set_refresh_token_to_cookie(request, response, tokens.refresh_token)return responsediff --git a/api/controllers/console/datasets/hit_testing_base.py b/api/controllers/console/datasets/hit_testing_base.pyindex 0e0a3114d98..a1a59cbd401 100644--- a/api/controllers/console/datasets/hit_testing_base.py+++ b/api/controllers/console/datasets/hit_testing_base.py@@ -5,7 +5,7 @@ from pydantic import BaseModel, Fieldfrom sqlalchemy.orm import Sessionfrom werkzeug.exceptions import Forbidden, InternalServerError, NotFound-import services+import services.errors.basefrom controllers.console.app.error import (CompletionRequestError,ProviderModelCurrentlyNotSupportError,@@ -97,7 +97,7 @@ class DatasetsHitTestingBase:try:DatasetService.check_dataset_permission(dataset, current_user, session)- except services.errors.account.NoPermissionError as e:+ except services.errors.base.NoPermissionError as e:raise Forbidden(str(e))return datasetdiff --git a/api/controllers/console/datasets/rag_pipeline/rag_pipeline.py b/api/controllers/console/datasets/rag_pipeline/rag_pipeline.pyindex a69f2fa37fb..6ae8232288d 100644--- a/api/controllers/console/datasets/rag_pipeline/rag_pipeline.py+++ b/api/controllers/console/datasets/rag_pipeline/rag_pipeline.py@@ -37,7 +37,7 @@ from models.account import Accountfrom models.dataset import Pipelinefrom repositories.knowledge.dataset_read_repository import get_pipeline_datasetfrom services.entities.knowledge_entities.rag_pipeline_entities import IconInfo, PipelineTemplateInfoEntity-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.errors.rag_pipeline import RagPipelineResourceNotFoundErrorfrom services.knowledge.dataset_service import DatasetServicefrom services.rag_pipeline.rag_pipeline import RagPipelineServicediff --git a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.pyindex 52898b07c34..08532d09cec 100644--- a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py+++ b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py@@ -9,7 +9,7 @@ from pydantic import BaseModel, Field, RootModel, ValidationErrorfrom sqlalchemy.orm import Session, sessionmakerfrom werkzeug.exceptions import BadRequest, Forbidden, InternalServerError, NotFound-import services+import services.errors.basefrom configs import dify_configfrom controllers.common.controller_schemas import DefaultBlockConfigQuery, WorkflowListQuery, WorkflowUpdatePayloadfrom controllers.common.fields import SimpleResultResponse@@ -1088,7 +1088,7 @@ class RagPipelineTransformApi(Resource):raise Forbidden()try:DatasetService.check_dataset_permission(dataset, current_user, session)- except services.errors.account.NoPermissionError as exc:+ except services.errors.base.NoPermissionError as exc:raise Forbidden(str(exc)) from exctry:diff --git a/api/controllers/console/flask_admission.py b/api/controllers/console/flask_admission.pyindex 7d492c04ee2..130651c132f 100644--- a/api/controllers/console/flask_admission.py+++ b/api/controllers/console/flask_admission.py@@ -10,22 +10,32 @@ from werkzeug.exceptions import Forbiddenfrom configs import dify_configfrom controllers.common.rbac import RBAC_CHECKS_ATTR, RBACCheck, enforce_rbac_checks+from controllers.console.admin import admin_requiredfrom controllers.console.wraps import (account_initialization_required,cloud_edition_billing_resource_check,enable_change_email,enterprise_license_required,+ is_allow_transfer_owner,setup_required,)from core.logging.context import get_request_id, get_trace_idfrom enums import DeploymentEdition+from enums.account import TenantAccountRolefrom libs.login import current_account_with_tenant, login_requiredfrom libs.oauth_bearer import bearer_feature_requiredfrom machinery.context import RequestContext-from models.account import TenantAccountRolefrom services.system_feature_service import SystemFeatureService+def console_admin_admission[T, **P, R](+ view: Callable[Concatenate[T, P], R],+) -> Callable[Concatenate[T, P], R]:+ """Admit a configured admin API key without requiring a Console account."""++ return setup_required(admin_required(view))++def console_email_registration_admission[T, **P, R](view: Callable[Concatenate[T, P], R],) -> Callable[Concatenate[T, P], R | Response]:@@ -49,28 +59,25 @@ def console_account_admission[T, **P, R](require_change_email_enabled: bool = False,require_initialized: bool = True,require_valid_enterprise_license: bool = False,+ require_owner_transfer_enabled: bool = False,+ billing_resource: str | None = None,require_oauth_bearer_enabled: bool = False,allowed_roles: frozenset[TenantAccountRole] | None = None,rbac_checks: Sequence[RBACCheck] | None = None,- billing_resource: str | None = None,) -> Callable[[Callable[Concatenate[T, RequestContext, P], R]],Callable[Concatenate[T, P], R | Response],]:"""Declare Console account admission and inject a stable RequestContext.- All combinations use this decorator factory. Requirements are data, while- the execution order stays fixed: edition, setup, login/CSRF, optional- account initialization, optional enterprise license and feature checks,- role/RBAC checks, then context construction and optional billing-resource- admission.+ Checks run in a fixed order: setup, login/CSRF, optional account+ initialization, edition, license, feature and billing checks, role/RBAC+ checks, then context construction."""def decorator(view: Callable[Concatenate[T, RequestContext, P], R],) -> Callable[Concatenate[T, P], R | Response]:- admitted_view = cloud_edition_billing_resource_check(billing_resource)(view) if billing_resource else view-@wraps(view)def inject_request_context(self: T, /, *args: P.args, **kwargs: P.kwargs) -> R:account_with_tenant = current_account_with_tenant()@@ -91,32 +98,40 @@ def console_account_admission[T, **P, R](request_id=get_request_id(),trace_id=get_trace_id() or request.headers.get("X-Trace-Id"),)- return admitted_view(self, request_context, *args, **kwargs)+ return view(self, request_context, *args, **kwargs)if rbac_checks is not None:setattr(inject_request_context, RBAC_CHECKS_ATTR, rbac_checks)admitted: Callable[Concatenate[T, P], R | Response] = inject_request_context+ if billing_resource is not None:+ admitted = cloud_edition_billing_resource_check(billing_resource)(admitted)if require_change_email_enabled:admitted = enable_change_email(admitted)+ if require_owner_transfer_enabled:+ admitted = is_allow_transfer_owner(admitted)if require_oauth_bearer_enabled:admitted = bearer_feature_required(admitted)if require_valid_enterprise_license:admitted = enterprise_license_required(admitted)+ if editions is not None:+ admitted = enforce_edition(admitted)if require_initialized:admitted = account_initialization_required(admitted)admitted = login_required(admitted)admitted = setup_required(admitted)- if editions is None:- return admitted+ return admitted- @wraps(view)- def enforce_edition(self: T, /, *args: P.args, **kwargs: P.kwargs) -> R | Response:- if dify_config.DEPLOYMENT_EDITION not in editions:+ def enforce_edition(+ admitted: Callable[Concatenate[T, P], R | Response],+ ) -> Callable[Concatenate[T, P], R | Response]:+ @wraps(admitted)+ def checked(self: T, /, *args: P.args, **kwargs: P.kwargs) -> R | Response:+ if editions is not None and dify_config.DEPLOYMENT_EDITION not in editions:abort(HTTPStatus.NOT_FOUND)return admitted(self, *args, **kwargs)- return enforce_edition+ return checkedreturn decoratordiff --git a/api/controllers/console/setup.py b/api/controllers/console/setup.pyindex 20fa631d057..e2d2bf15480 100644--- a/api/controllers/console/setup.py+++ b/api/controllers/console/setup.py@@ -7,11 +7,8 @@ from controllers.fastopenapi import console_routerfrom extensions.ext_application_services import application_servicesfrom libs.helper import EmailStr, extract_remote_ipfrom libs.password import valid_password-from services.setup_service import (- InitializationValidationRequiredError,- SetupAlreadyCompletedError,- SetupInput,-)+from services.account.contracts import SetupInput+from services.setup_service import InitializationValidationRequiredError, SetupAlreadyCompletedErrorfrom .error import AlreadySetupError, NotInitValidateErrorfrom .init_validate import is_init_validateddiff --git a/api/controllers/console/socketio/workflow.py b/api/controllers/console/socketio/workflow.pyindex 4569310bbe4..13555b1a973 100644--- a/api/controllers/console/socketio/workflow.py+++ b/api/controllers/console/socketio/workflow.py@@ -5,11 +5,11 @@ from typing import castfrom flask import Request as FlaskRequestfrom core.db.session_factory import session_factory+from extensions.ext_application_services import application_servicesfrom extensions.ext_socketio import siofrom libs.passport import PassportServicefrom libs.token import extract_access_tokenfrom repositories.workflow_collaboration_repository import WorkflowCollaborationRepository-from services.account_service import AccountServicefrom services.workflow_collaboration_service import WorkflowCollaborationServicerepository = WorkflowCollaborationRepository()@@ -43,8 +43,8 @@ def socket_connect(sid, environ, auth):logging.warning("Socket connect rejected: missing user_id (sid=%s)", sid)return False- with sio.app.app_context(), session_factory.create_session() as session:- user = AccountService.load_logged_in_account(account_id=user_id, session=session)+ with sio.app.app_context():+ user = application_services().accounts.identity.load_user(user_id)if not user:logging.warning("Socket connect rejected: user not found (user_id=%s, sid=%s)", user_id, sid)return Falsediff --git a/api/controllers/console/workspace/members.py b/api/controllers/console/workspace/members.pyindex 6587cce55fe..391aa52637d 100644--- a/api/controllers/console/workspace/members.py+++ b/api/controllers/console/workspace/members.py@@ -1,15 +1,13 @@from http import HTTPStatus-from typing import Annotated, Literal+from typing import Annotated, Literal, NoReturnfrom urllib import parsefrom uuid import UUID-from flask import abort, request+from flask import requestfrom flask_restx import Resourcefrom pydantic import BaseModel, Field, field_validator-from sqlalchemy import func, select-from werkzeug.exceptions import NotFound+from werkzeug.exceptions import Forbidden, NotFound-import servicesfrom configs import dify_configfrom controllers.common.fields import SimpleResultDataResponse, SimpleResultResponse, VerificationTokenResponsefrom controllers.common.schema import register_enum_models, register_response_schema_models, register_schema_models@@ -22,30 +20,25 @@ from controllers.console.auth.error import (MemberNotInTenantError,NotOwnerError,OwnerTransferLimitError,+ OwnerTransferRateLimitExceededError,)from controllers.console.error import EmailSendIpLimitError, SeatsLimitExceeded, WorkspaceMembersLimitExceededfrom controllers.console.flask_admission import console_account_admissionfrom controllers.console.workspace.error import InvalidMemberRoleError-from controllers.console.wraps import (- account_initialization_required,- is_allow_transfer_owner,- setup_required,- with_current_user,-)-from enums import DeploymentEdition+from enums.account import TenantAccountRolefrom extensions.ext_application_services import application_services-from extensions.ext_database import db-from extensions.ext_redis import redis_clientfrom fields.base import ResponseModelfrom fields.member_fields import AccountWithRoleListResponse, AccountWithRoleResponsefrom libs.helper import dump_response, extract_remote_ip-from libs.login import login_requiredfrom machinery.context import RequestContext-from models.account import Account, TenantAccountJoin, TenantAccountRole-from services.account_service import AccountService, RegisterService, TenantService-from services.errors.account import AccountAlreadyInTenantError-from services.feature_service import FeatureService-from services.system_feature_service import SystemFeatureService+from services.account_errors import AccountNotFoundError+from services.errors import workspace as workspace_errors+from services.errors.base import NoPermissionError+from services.errors.workspace import (+ InvalidWorkspaceMemberRoleError,+ WorkspaceApplicationError,+ WorkspaceInvitationQuotaError,+)class MemberInvitePayload(BaseModel):@@ -142,62 +135,6 @@ register_response_schema_models()-def _is_role_enabled(role: TenantAccountRole | str) -> bool:- if role != TenantAccountRole.DATASET_OPERATOR:- return True- return dify_config.DATASET_OPERATOR_ENABLED---def _count_new_member_invites(tenant_id: str, emails: list[str]) -> tuple[int, int]:- new_member_count = 0- new_account_count = 0- for email in emails:- account = AccountService.get_account_by_email_with_case_fallback(email, session=db.session())- if not account:- new_member_count += 1- new_account_count += 1- continue-- exists = db.session.scalar(- select(TenantAccountJoin.id)- .where(TenantAccountJoin.tenant_id == tenant_id, TenantAccountJoin.account_id == account.id)- .limit(1)- )- if not exists:- new_member_count += 1-- return new_member_count, new_account_count---def _count_current_members(tenant_id: str) -> int:- return (- db.session.scalar(select(func.count(TenantAccountJoin.id)).where(TenantAccountJoin.tenant_id == tenant_id)) or 0- )---def _check_member_invite_limits(tenant_id: str, new_member_count: int, new_account_count: int) -> None:- if new_member_count <= 0:- return-- features = FeatureService.get_features(tenant_id=tenant_id, exclude_vector_space=True)-- if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.ENTERPRISE:- workspace_members = features.workspace_members- if workspace_members.enabled is True and not workspace_members.is_available(new_member_count):- raise WorkspaceMembersLimitExceeded()- if new_account_count > 0:- seats = SystemFeatureService.get_license().seats- if not seats.is_available(new_account_count):- raise SeatsLimitExceeded()- return-- if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:- members = features.members- current_member_count = _count_current_members(tenant_id)- if 0 < members.limit < current_member_count + new_member_count:- raise WorkspaceMembersLimitExceeded()--@console_ns.route("/workspaces/current/members")class MemberListApi(Resource):"""List all members of current tenant."""@@ -205,7 +142,7 @@ class MemberListApi(Resource):@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[AccountWithRoleListResponse.__name__])@console_account_admission()def get(self, request_context: RequestContext):- members = application_services().workspace_member_queries.list_current(request_context)+ members = application_services().workspaces.member_queries.list_current(request_context)serialized_members = [{"id": member.id,@@ -235,123 +172,68 @@ class MemberInviteEmailApi(Resource):"Invalid role or workspace member limit exceeded",console_ns.models[MemberInviteErrorResponse.__name__],)- @setup_required- @login_required- @account_initialization_required- @with_current_user- def post(self, current_user: Account):- payload = console_ns.payload or {}- args = MemberInvitePayload.model_validate(payload)-- invitee_emails = args.emails- invitee_role = args.role- interface_language = args.language- if not dify_config.RBAC_ENABLED:- if not TenantAccountRole.is_valid_role(invitee_role):- raise InvalidMemberRoleError()- if not TenantAccountRole.is_non_owner_role(TenantAccountRole(invitee_role)):- raise InvalidMemberRoleError()- inviter = current_user- if not inviter.current_tenant:- raise ValueError("No current tenant")- if not _is_role_enabled(invitee_role):- raise InvalidMemberRoleError()-- # Check workspace permission for member invitations- from libs.workspace_permission import check_workspace_member_invite_permission-- check_workspace_member_invite_permission(inviter.current_tenant.id)-- invitation_results: list[MemberInviteResultResponse] = []- console_web_url = dify_config.CONSOLE_WEB_URL-- tenant_id = inviter.current_tenant.id- with redis_client.lock(f"workspace_member_invite:{tenant_id}", timeout=60):- if dify_config.DEPLOYMENT_EDITION in {- DeploymentEdition.CLOUD,- DeploymentEdition.ENTERPRISE,- }:- new_member_count, new_account_count = _count_new_member_invites(tenant_id, invitee_emails)- _check_member_invite_limits(tenant_id, new_member_count, new_account_count)-- for invitee_email in invitee_emails:- try:- if not inviter.current_tenant:- raise ValueError("No current tenant")- token = RegisterService.invite_new_member(- tenant=inviter.current_tenant,- email=invitee_email,- language=interface_language,- role=invitee_role,- inviter=inviter,- session=db.session(),- )- encoded_invitee_email = parse.quote(invitee_email)- invitation_results.append(- MemberInviteSuccessResponse(- status="success",- email=invitee_email,- url=f"{console_web_url}/activate?email={encoded_invitee_email}&token={token}",- )- )- except AccountAlreadyInTenantError:- invitation_results.append(- MemberInviteAlreadyMemberResponse(- status="already_member",- email=invitee_email,- message="Account already in workspace.",- )+ @console_account_admission()+ def post(self, request_context: RequestContext):+ args = MemberInvitePayload.model_validate(console_ns.payload or {})+ try:+ results = application_services().workspaces.invitations.invite_many(+ request_context,+ emails=args.emails,+ language=args.language,+ role=args.role,+ )+ except InvalidWorkspaceMemberRoleError:+ raise InvalidMemberRoleError() from None+ except NoPermissionError as error:+ raise Forbidden(str(error)) from error+ except WorkspaceInvitationQuotaError as error:+ if error.seats:+ raise SeatsLimitExceeded() from error+ raise WorkspaceMembersLimitExceeded() from error+ serialized: list[MemberInviteResultResponse] = []+ for result in results:+ if result.status == "success":+ email = parse.quote(result.email)+ serialized.append(+ MemberInviteSuccessResponse(+ status="success",+ email=result.email,+ url=f"{dify_config.CONSOLE_WEB_URL}/activate?email={email}&token={result.token}",)- except Exception as e:- invitation_results.append(- MemberInviteFailedResponse(status="failed", email=invitee_email, message=str(e))+ )+ elif result.status == "already_member":+ serialized.append(+ MemberInviteAlreadyMemberResponse(+ status="already_member", email=result.email, message=result.message or "")-- return (- dump_response(- MemberInviteResponse,- {- "result": "success",- "invitation_results": invitation_results,- "tenant_id": inviter.current_tenant.id if inviter.current_tenant else "",- },- ),- HTTPStatus.CREATED,- )+ )+ else:+ serialized.append(+ MemberInviteFailedResponse(status="failed", email=result.email, message=result.message or "")+ )+ return dump_response(+ MemberInviteResponse,+ {"result": "success", "invitation_results": serialized, "tenant_id": request_context.active_workspace_id},+ ), HTTPStatus.CREATED@console_ns.route("/workspaces/current/members/<uuid:member_id>")class MemberCancelInviteApi(Resource):"""Cancel an invitation by member id."""- @setup_required- @login_required- @account_initialization_required@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[MemberActionResponse.__name__])- @with_current_user- def delete(self, current_user: Account, member_id: UUID):- if not current_user.current_tenant:- raise ValueError("No current tenant")- member = db.session.get(Account, str(member_id))- if member is None:- abort(HTTPStatus.NOT_FOUND)- else:- try:- TenantService.remove_member_from_tenant(- current_user.current_tenant, member, current_user, session=db.session()- )- except services.errors.account.CannotOperateSelfError as e:- return {"code": "cannot-operate-self", "message": str(e)}, HTTPStatus.BAD_REQUEST- except services.errors.account.NoPermissionError as e:- return {"code": "forbidden", "message": str(e)}, HTTPStatus.FORBIDDEN- except services.errors.account.MemberNotInTenantError as e:- return {"code": "member-not-found", "message": str(e)}, HTTPStatus.NOT_FOUND- except Exception as e:- raise ValueError(str(e))+ @console_account_admission()+ def delete(self, request_context: RequestContext, member_id: UUID):+ try:+ application_services().workspaces.members.remove(+ request_context.active_workspace_id, str(member_id), request_context.account_id+ )+ except (WorkspaceApplicationError, AccountNotFoundError, NoPermissionError) as error:+ return _member_mutation_error_response(error)return MemberActionResponse(result="success",- tenant_id=current_user.current_tenant.id if current_user.current_tenant else "",+ tenant_id=request_context.active_workspace_id,).model_dump(mode="json"), HTTPStatus.OK@@ -361,40 +243,16 @@ class MemberUpdateRoleApi(Resource):@console_ns.expect(console_ns.models[MemberRoleUpdatePayload.__name__])@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[SimpleResultResponse.__name__])- @setup_required- @login_required- @account_initialization_required- @with_current_user- def put(self, current_user: Account, member_id: UUID):+ @console_account_admission()+ def put(self, request_context: RequestContext, member_id: UUID):payload = console_ns.payload or {}args = MemberRoleUpdatePayload.model_validate(payload)- new_role = args.role-- if not TenantAccountRole.is_valid_role(new_role):- return {"code": "invalid-role", "message": "Invalid role"}, HTTPStatus.BAD_REQUEST- if not current_user.current_tenant:- raise ValueError("No current tenant")- if not _is_role_enabled(new_role):- return {"code": "invalid-role", "message": "Invalid role"}, HTTPStatus.BAD_REQUEST- member = db.session.get(Account, str(member_id))- if not member:- abort(HTTPStatus.NOT_FOUND)-try:- assert member is not None, "Member not found"- TenantService.update_member_role(- current_user.current_tenant, member, new_role, current_user, session=db.session()+ application_services().workspaces.members.update_role(+ request_context.active_workspace_id, str(member_id), args.role, request_context.account_id)- except services.errors.account.CannotOperateSelfError as e:- return {"code": "cannot-operate-self", "message": str(e)}, HTTPStatus.BAD_REQUEST- except services.errors.account.NoPermissionError as e:- return {"code": "forbidden", "message": str(e)}, HTTPStatus.FORBIDDEN- except services.errors.account.MemberNotInTenantError as e:- return {"code": "member-not-found", "message": str(e)}, HTTPStatus.NOT_FOUND- except services.errors.account.RoleAlreadyAssignedError as e:- return {"code": "role-already-assigned", "message": str(e)}, HTTPStatus.BAD_REQUEST- except Exception as e:- raise ValueError(str(e))+ except (WorkspaceApplicationError, AccountNotFoundError, NoPermissionError) as error:+ return _member_mutation_error_response(error)return SimpleResultResponse(result="success").model_dump(mode="json")@@ -403,15 +261,12 @@ class MemberUpdateRoleApi(Resource):class DatasetOperatorMemberListApi(Resource):"""List all members of current tenant."""- @setup_required- @login_required- @account_initialization_required@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[AccountWithRoleListResponse.__name__])- @with_current_user- def get(self, current_user: Account):- if not current_user.current_tenant:- raise ValueError("No current tenant")- members = TenantService.get_dataset_operator_members(current_user.current_tenant, session=db.session())+ @console_account_admission()+ def get(self, request_context: RequestContext):+ members = application_services().workspaces.member_queries.list_members(+ request_context.active_workspace_id, dataset_operators_only=True+ )return dump_response(AccountWithRoleListResponse, {"accounts": members}), HTTPStatus.OK@@ -421,37 +276,17 @@ class SendOwnerTransferEmailApi(Resource):@console_ns.expect(console_ns.models[OwnerTransferEmailPayload.__name__])@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[SimpleResultDataResponse.__name__])- @setup_required- @login_required- @account_initialization_required- @is_allow_transfer_owner- @with_current_user- def post(self, current_user: Account):- payload = console_ns.payload or {}- args = OwnerTransferEmailPayload.model_validate(payload)- ip_address = extract_remote_ip(request)- if AccountService.is_email_send_ip_limit(ip_address):- raise EmailSendIpLimitError()- # check if the current user is the owner of the workspace- if not current_user.current_tenant:- raise ValueError("No current tenant")- if not TenantService.is_owner(current_user, current_user.current_tenant, session=db.session()):- raise NotOwnerError()-- if args.language is not None and args.language == "zh-Hans":- language = "zh-Hans"- else:- language = "en-US"-- email = current_user.email-- token = AccountService.send_owner_transfer_email(- account=current_user,- email=email,- language=language,- workspace_name=current_user.current_tenant.name if current_user.current_tenant else "",- )-+ @console_account_admission(require_owner_transfer_enabled=True)+ def post(self, request_context: RequestContext):+ args = OwnerTransferEmailPayload.model_validate(console_ns.payload or {})+ try:+ token = application_services().workspaces.owner_transfer.send_code(+ request_context,+ ip_address=extract_remote_ip(request),+ language=args.language,+ )+ except (WorkspaceApplicationError, AccountNotFoundError, NoPermissionError) as error:+ _raise_owner_transfer_error(error)return SimpleResultDataResponse(result="success", data=token).model_dump(mode="json")@@ -459,107 +294,73 @@ class SendOwnerTransferEmailApi(Resource):class OwnerTransferCheckApi(Resource):@console_ns.expect(console_ns.models[OwnerTransferCheckPayload.__name__])@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[VerificationTokenResponse.__name__])- @setup_required- @login_required- @account_initialization_required- @is_allow_transfer_owner- @with_current_user- def post(self, current_user: Account):- payload = console_ns.payload or {}- args = OwnerTransferCheckPayload.model_validate(payload)- # check if the current user is the owner of the workspace- if not current_user.current_tenant:- raise ValueError("No current tenant")- if not TenantService.is_owner(current_user, current_user.current_tenant, session=db.session()):- raise NotOwnerError()-- user_email = current_user.email-- is_owner_transfer_error_rate_limit = AccountService.is_owner_transfer_error_rate_limit(user_email)- if is_owner_transfer_error_rate_limit:- raise OwnerTransferLimitError()-- token_data = AccountService.get_owner_transfer_data(args.token)- if token_data is None:- raise InvalidTokenError()-- if user_email != token_data.get("email"):- raise InvalidEmailError()-- if args.code != token_data.get("code"):- AccountService.add_owner_transfer_error_rate_limit(user_email)- raise EmailCodeError()-- # Verified, revoke the first token- AccountService.revoke_owner_transfer_token(args.token)-- # Refresh token data by generating a new token- _, new_token = AccountService.generate_owner_transfer_token(user_email, code=args.code, additional_data={})-- AccountService.reset_owner_transfer_error_rate_limit(user_email)- return VerificationTokenResponse(is_valid=True, email=user_email, token=new_token).model_dump(mode="json")+ @console_account_admission(require_owner_transfer_enabled=True)+ def post(self, request_context: RequestContext):+ args = OwnerTransferCheckPayload.model_validate(console_ns.payload or {})+ try:+ email, token = application_services().workspaces.owner_transfer.verify_code(+ request_context, token=args.token, code=args.code+ )+ except (WorkspaceApplicationError, AccountNotFoundError, NoPermissionError) as error:+ _raise_owner_transfer_error(error)+ return VerificationTokenResponse(is_valid=True, email=email, token=token).model_dump(mode="json")@console_ns.route("/workspaces/current/members/<uuid:member_id>/owner-transfer")class OwnerTransfer(Resource):@console_ns.expect(console_ns.models[OwnerTransferPayload.__name__])@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[SimpleResultResponse.__name__])- @setup_required- @login_required- @account_initialization_required- @is_allow_transfer_owner- @with_current_user- def post(self, current_user: Account, member_id: UUID):- payload = console_ns.payload or {}- args = OwnerTransferPayload.model_validate(payload)-- # check if the current user is the owner of the workspace- if not current_user.current_tenant:- raise ValueError("No current tenant")- if not TenantService.is_owner(current_user, current_user.current_tenant, session=db.session()):- raise NotOwnerError()-- if current_user.id == str(member_id):- raise CannotTransferOwnerToSelfError()-- transfer_token_data = AccountService.get_owner_transfer_data(args.token)- if not transfer_token_data:- raise InvalidTokenError()-- if transfer_token_data.get("email") != current_user.email:- raise InvalidEmailError()-- AccountService.revoke_owner_transfer_token(args.token)-- member = db.session.get(Account, str(member_id))- if not member:- raise NotFound()-- if not current_user.current_tenant:- raise ValueError("No current tenant")- if not TenantService.is_member(member, current_user.current_tenant, session=db.session()):- raise MemberNotInTenantError()-+ @console_account_admission(require_owner_transfer_enabled=True)+ def post(self, request_context: RequestContext, member_id: UUID):+ args = OwnerTransferPayload.model_validate(console_ns.payload or {})try:- assert member is not None, "Member not found"- TenantService.update_member_role(- current_user.current_tenant, member, "owner", current_user, session=db.session()- )-- AccountService.send_new_owner_transfer_notify_email(- account=member,- email=member.email,- workspace_name=current_user.current_tenant.name if current_user.current_tenant else "",- )-- AccountService.send_old_owner_transfer_notify_email(- account=current_user,- email=current_user.email,- workspace_name=current_user.current_tenant.name if current_user.current_tenant else "",- new_owner_email=member.email,+ application_services().workspaces.owner_transfer.transfer(+ request_context, member_id=str(member_id), token=args.token)+ except (WorkspaceApplicationError, AccountNotFoundError, NoPermissionError) as error:+ _raise_owner_transfer_error(error)+ return SimpleResultResponse(result="success").model_dump(mode="json")- except Exception as e:- raise ValueError(str(e))- return SimpleResultResponse(result="success").model_dump(mode="json")+def _member_mutation_error_response(+ error: WorkspaceApplicationError | AccountNotFoundError | NoPermissionError,+) -> tuple[dict[str, str], HTTPStatus]:+ if isinstance(error, (AccountNotFoundError, workspace_errors.WorkspaceNotFoundError)):+ raise NotFound() from error+ if isinstance(error, InvalidWorkspaceMemberRoleError):+ return {"code": "invalid-role", "message": "Invalid role"}, HTTPStatus.BAD_REQUEST+ if isinstance(error, workspace_errors.CannotOperateSelfError):+ return {"code": "cannot-operate-self", "message": str(error)}, HTTPStatus.BAD_REQUEST+ if isinstance(error, NoPermissionError):+ return {"code": "forbidden", "message": str(error)}, HTTPStatus.FORBIDDEN+ if isinstance(error, workspace_errors.MemberNotInTenantError):+ return {"code": "member-not-found", "message": str(error)}, HTTPStatus.NOT_FOUND+ if isinstance(error, workspace_errors.RoleAlreadyAssignedError):+ return {"code": "role-already-assigned", "message": str(error)}, HTTPStatus.BAD_REQUEST+ raise error+++def _raise_owner_transfer_error(+ error: WorkspaceApplicationError | AccountNotFoundError | NoPermissionError,+) -> NoReturn:+ if isinstance(error, NoPermissionError):+ raise NotOwnerError() from error+ if isinstance(error, (AccountNotFoundError, workspace_errors.WorkspaceNotFoundError)):+ raise NotFound() from error+ if isinstance(error, workspace_errors.OwnerTransferSendIPLimitedError):+ raise EmailSendIpLimitError() from error+ if isinstance(error, workspace_errors.OwnerTransferSendRateLimitError):+ raise OwnerTransferRateLimitExceededError(error.retry_after_minutes) from error+ if isinstance(error, workspace_errors.OwnerTransferVerificationLimitError):+ raise OwnerTransferLimitError() from error+ if isinstance(error, workspace_errors.InvalidOwnerTransferTokenError):+ raise InvalidTokenError() from error+ if isinstance(error, workspace_errors.InvalidOwnerTransferEmailError):+ raise InvalidEmailError() from error+ if isinstance(error, workspace_errors.InvalidOwnerTransferCodeError):+ raise EmailCodeError() from error+ if isinstance(error, workspace_errors.CannotOperateSelfError):+ raise CannotTransferOwnerToSelfError() from error+ if isinstance(error, workspace_errors.MemberNotInTenantError):+ raise MemberNotInTenantError() from error+ raise errordiff --git a/api/controllers/console/workspace/model_providers.py b/api/controllers/console/workspace/model_providers.pyindex 23f467ef8be..3b70e677b05 100644--- a/api/controllers/console/workspace/model_providers.py+++ b/api/controllers/console/workspace/model_providers.py@@ -4,12 +4,10 @@ from typing import Any, Literalfrom flask import send_filefrom flask_restx import Resourcefrom pydantic import BaseModel, Field, field_validator-from sqlalchemy.orm import Sessionfrom controllers.common.fields import SimpleResultResponse, ValidationResultResponsefrom controllers.common.rbac import RBACCheck, Workspacefrom controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models-from controllers.common.session import with_sessionfrom controllers.console import console_nsfrom controllers.console.wraps import (RBACPermission,@@ -21,6 +19,7 @@ from controllers.console.wraps import (with_current_tenant_id,with_current_user,)+from extensions.ext_application_services import application_servicesfrom fields.base import ResponseModelfrom graphon.model_runtime.entities.model_entities import ModelTypefrom graphon.model_runtime.errors.validate import CredentialsValidateFailedError@@ -34,7 +33,6 @@ from services.entities.model_provider_entities import (ProviderResponse,)from services.model_provider.service import ModelProviderService-from services.workspace_service import WorkspaceServiceclass ParserModelList(BaseModel):@@ -191,9 +189,8 @@ class ModelProviderCreditsApi(Resource):@login_required@account_initialization_required@with_current_tenant_id- @with_session(write=False)- def get(self, session: Session, tenant_id: str):- credit_pool = WorkspaceService.get_effective_credit_pool(tenant_id, session=session)+ def get(self, tenant_id: str):+ credit_pool = application_services().workspaces.management.get_effective_credit_pool(tenant_id)return dump_response(ModelProviderCreditsResponse, credit_pool)diff --git a/api/controllers/console/workspace/workspace.py b/api/controllers/console/workspace/workspace.pyindex 38c21bc8d44..66db750de78 100644--- a/api/controllers/console/workspace/workspace.py+++ b/api/controllers/console/workspace/workspace.py@@ -1,16 +1,11 @@-import loggingfrom datetime import datetimefrom http import HTTPStatusfrom flask import requestfrom flask_restx import Resourcefrom pydantic import BaseModel, Field, field_validator-from sqlalchemy import select-from sqlalchemy.orm import Sessionfrom werkzeug.exceptions import NotFound-import services-from configs import dify_configfrom controllers.common.errors import (FilenameNotExistsError,FileTooLargeError,@@ -24,35 +19,19 @@ from controllers.common.schema import (register_response_schema_models,register_schema_models,)-from controllers.common.session import with_sessionfrom controllers.console import console_ns-from controllers.console.admin import admin_requiredfrom controllers.console.error import AccountNotLinkTenantError-from controllers.console.flask_admission import console_account_admission+from controllers.console.flask_admission import console_account_admission, console_admin_admissionfrom controllers.console.workspace.error import CurrentWorkspaceArchivedError-from controllers.console.wraps import (- account_initialization_required,- cloud_edition_billing_resource_check,- only_edition_enterprise,- setup_required,- with_current_tenant_id,- with_current_user,-)-from enums import CloudPlan+from enums import CloudPlan, DeploymentEdition+from enums.account import TenantAccountRolefrom extensions.ext_application_services import application_services-from extensions.ext_database import dbfrom fields.base import ResponseModelfrom libs.helper import dump_response, to_timestamp-from libs.login import login_required-from libs.pagination import paginate_queryfrom machinery.context import RequestContext-from models.account import Account, Tenant, TenantAccountRole, TenantCustomConfigDict, TenantStatus-from services.account_service import TenantService-from services.enterprise.enterprise_service import EnterpriseService-from services.file_service import FileService-from services.workspace_service import WorkspaceService--logger = logging.getLogger(__name__)+from services.errors import file as file_errors+from services.errors.workspace import WorkspaceArchivedError, WorkspaceNotFoundError, WorkspaceNotLinkedError+from services.workspace.contracts import WorkspaceCustomConfigChangesclass WorkspaceListQuery(BaseModel):@@ -231,7 +210,7 @@ class TenantListApi(Resource):@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[TenantListResponse.__name__])@console_account_admission()def get(self, request_context: RequestContext):- workspaces = application_services().workspace_queries.list_for_account(request_context)+ workspaces = application_services().workspaces.queries.list_for_account(request_context)return dump_response(TenantListResponse, {"workspaces": workspaces}), HTTPStatus.OK@@ -239,207 +218,108 @@ class TenantListApi(Resource):class WorkspaceListApi(Resource):@console_ns.doc(params=query_params_from_model(WorkspaceListQuery))@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[WorkspacePaginationResponse.__name__])- @setup_required- @admin_required- @with_session(write=False)- def get(self, session: Session):+ @console_admin_admission+ def get(self):args = query_params_from_request(WorkspaceListQuery)-- stmt = select(Tenant).order_by(Tenant.created_at.desc())- tenants = paginate_query(stmt, session=session, page=args.page, per_page=args.limit)- has_more = False-- if tenants.has_next:- has_more = True-- return WorkspacePaginationResponse(- data=tenants.items, has_more=has_more, limit=args.limit, page=args.page, total=tenants.total or 0- ).model_dump(mode="json"), HTTPStatus.OK+ result = application_services().workspaces.management.list_all(page=args.page, limit=args.limit)+ return dump_response(WorkspacePaginationResponse, result), HTTPStatus.OK@console_ns.route("/workspaces/current/summary")class CurrentWorkspaceSummaryApi(Resource):- @console_ns.response(- HTTPStatus.OK,- "Success",- console_ns.models[CurrentWorkspaceSummaryResponse.__name__],- )+ @console_ns.response(HTTPStatus.OK, "Success", console_ns.models[CurrentWorkspaceSummaryResponse.__name__])@console_ns.response(HTTPStatus.CONFLICT, "Current workspace is archived")- @setup_required- @login_required- @account_initialization_required- @with_current_user- @with_session(write=False)- def get(self, session: Session, current_user: Account):- tenant = current_user.current_tenant- if not tenant:- raise ValueError("No current tenant")- if tenant.status == TenantStatus.ARCHIVE:- raise CurrentWorkspaceArchivedError()-- return (- dump_response(- CurrentWorkspaceSummaryResponse,- WorkspaceService.get_current_workspace_summary(tenant, current_user.id, session=session),- ),- HTTPStatus.OK,- )+ @console_account_admission()+ def get(self, context: RequestContext):+ try:+ summary = application_services().workspaces.management.current_summary(context)+ except WorkspaceArchivedError as exc:+ raise CurrentWorkspaceArchivedError() from exc+ except WorkspaceNotFoundError as exc:+ raise NotFound() from exc+ return dump_response(CurrentWorkspaceSummaryResponse, summary), HTTPStatus.OK@console_ns.route("/workspaces/switch")class SwitchWorkspaceApi(Resource):@console_ns.expect(console_ns.models[SwitchWorkspacePayload.__name__])@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[SwitchWorkspaceResponse.__name__])- @setup_required- @login_required- @account_initialization_required- @with_current_user- @with_session- def post(self, session: Session, current_user: Account):- payload = console_ns.payload or {}- args = SwitchWorkspacePayload.model_validate(payload)-- # Check whether the tenant_id belongs to the current account.+ @console_account_admission()+ def post(self, context: RequestContext):+ args = SwitchWorkspacePayload.model_validate(console_ns.payload or {})try:- TenantService.switch_tenant(current_user, args.tenant_id, session=session)- except Exception as e:- raise AccountNotLinkTenantError("Account not link tenant") from e-- new_tenant = TenantService.get_tenant_by_id(args.tenant_id, session=session)- if new_tenant is None:- raise ValueError("Tenant not found")-- return SwitchWorkspaceResponse(- result="success", new_tenant=WorkspaceService.get_tenant_info(new_tenant, session=session)- ).model_dump(mode="json")+ tenant = application_services().workspaces.management.switch(context, args.tenant_id)+ except WorkspaceNotLinkedError as exc:+ raise AccountNotLinkTenantError("Account not link tenant") from exc+ except WorkspaceNotFoundError as exc:+ raise NotFound() from exc+ return dump_response(SwitchWorkspaceResponse, {"result": "success", "new_tenant": tenant})@console_ns.route("/workspaces/custom-config")class CustomConfigWorkspaceApi(Resource):@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[WorkspaceCustomConfigResponse.__name__])- @setup_required- @login_required- @account_initialization_required- @with_current_tenant_id- @with_session(write=False)- def get(self, session: Session, current_tenant_id: str):- tenant = TenantService.get_tenant_by_id(current_tenant_id, session=session)- if tenant is None:- raise NotFound()-- custom_config = tenant.custom_config_dict- replace_webapp_logo = (- f"{dify_config.FILES_URL}/files/workspaces/{tenant.id}/webapp-logo"- if custom_config.get("replace_webapp_logo")- else None- )- return dump_response(- WorkspaceCustomConfigResponse,- {- "remove_webapp_brand": custom_config.get("remove_webapp_brand", False),- "replace_webapp_logo": replace_webapp_logo,- },- )+ @console_account_admission()+ def get(self, context: RequestContext):+ try:+ config = application_services().workspaces.management.custom_config(context)+ except WorkspaceNotFoundError as exc:+ raise NotFound() from exc+ return dump_response(WorkspaceCustomConfigResponse, config)@console_ns.expect(console_ns.models[WorkspaceCustomConfigPayload.__name__])@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[WorkspaceTenantResultResponse.__name__])- @setup_required- @login_required- @account_initialization_required- @cloud_edition_billing_resource_check("workspace_custom")- @with_current_tenant_id- @with_session- def post(self, session: Session, current_tenant_id: str):- payload = console_ns.payload or {}- args = WorkspaceCustomConfigPayload.model_validate(payload)- tenant = TenantService.get_tenant_by_id(current_tenant_id, session=session)- if tenant is None:- raise NotFound()-- custom_config_dict: TenantCustomConfigDict = {- "remove_webapp_brand": args.remove_webapp_brand- if args.remove_webapp_brand is not None- else tenant.custom_config_dict.get("remove_webapp_brand", False),- "replace_webapp_logo": args.replace_webapp_logo- if args.replace_webapp_logo is not None- else tenant.custom_config_dict.get("replace_webapp_logo"),- }-- tenant.custom_config_dict = custom_config_dict- session.commit()-- return WorkspaceTenantResultResponse(- result="success", tenant=WorkspaceService.get_tenant_info(tenant, session=session)- ).model_dump(mode="json")+ @console_account_admission(billing_resource="workspace_custom")+ def post(self, context: RequestContext):+ args = WorkspaceCustomConfigPayload.model_validate(console_ns.payload or {})+ try:+ tenant = application_services().workspaces.management.update_custom_config(+ context,+ WorkspaceCustomConfigChanges(+ remove_webapp_brand=args.remove_webapp_brand, replace_webapp_logo=args.replace_webapp_logo+ ),+ )+ except WorkspaceNotFoundError as exc:+ raise NotFound() from exc+ return dump_response(WorkspaceTenantResultResponse, {"result": "success", "tenant": tenant})@console_ns.route("/workspaces/custom-config/webapp-logo/upload")class WebappLogoWorkspaceApi(Resource):@console_ns.doc(consumes=["multipart/form-data"], params=WORKSPACE_LOGO_UPLOAD_PARAMS)@console_ns.response(HTTPStatus.CREATED, "Logo uploaded", console_ns.models[WorkspaceLogoUploadResponse.__name__])- @setup_required- @login_required- @account_initialization_required- @cloud_edition_billing_resource_check("workspace_custom")- @with_current_user- def post(self, current_user: Account):- # check file+ @console_account_admission(billing_resource="workspace_custom")+ def post(self, context: RequestContext):if "file" not in request.files:raise NoFileUploadedError()-if len(request.files) > 1:raise TooManyFilesError()-- # get file from requestfile = request.files["file"]if not file.filename:- raise FilenameNotExistsError-- extension = file.filename.split(".")[-1]- if extension.lower() not in {"svg", "png"}:- raise UnsupportedFileTypeError()-+ raise FilenameNotExistsError()try:- upload_file = FileService(db.engine).upload_file(- filename=file.filename,- content=file.stream.read(),- mimetype=file.mimetype,- user=current_user,+ file_id = application_services().workspaces.management.upload_logo(+ context, filename=file.filename, content=file.stream.read(), mimetype=file.mimetype)-- except services.errors.file.FileTooLargeError as file_too_large_error:- raise FileTooLargeError(file_too_large_error.description)- except services.errors.file.UnsupportedFileTypeError:- raise UnsupportedFileTypeError()-- return WorkspaceLogoUploadResponse(id=upload_file.id).model_dump(mode="json"), HTTPStatus.CREATED+ except file_errors.FileTooLargeError as exc:+ raise FileTooLargeError(exc.description) from exc+ except file_errors.UnsupportedFileTypeError as exc:+ raise UnsupportedFileTypeError() from exc+ return dump_response(WorkspaceLogoUploadResponse, {"id": file_id}), HTTPStatus.CREATED@console_ns.route("/workspaces/info")class WorkspaceInfoApi(Resource):@console_ns.expect(console_ns.models[WorkspaceInfoPayload.__name__])@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[WorkspaceTenantResultResponse.__name__])- @setup_required- @login_required- @account_initialization_required- # Change workspace name- @with_current_tenant_id- @with_session- def post(self, session: Session, current_tenant_id: str):- payload = console_ns.payload or {}- args = WorkspaceInfoPayload.model_validate(payload)-- if not current_tenant_id:- raise ValueError("No current tenant")- tenant = TenantService.get_tenant_by_id(current_tenant_id, session=session)- if tenant is None:- raise NotFound()- tenant.name = args.name- session.commit()-- return WorkspaceTenantResultResponse(- result="success", tenant=WorkspaceService.get_tenant_info(tenant, session=session)- ).model_dump(mode="json")+ @console_account_admission()+ def post(self, context: RequestContext):+ args = WorkspaceInfoPayload.model_validate(console_ns.payload or {})+ try:+ tenant = application_services().workspaces.management.rename(context, args.name)+ except WorkspaceNotFoundError as exc:+ raise NotFound() from exc+ return dump_response(WorkspaceTenantResultResponse, {"result": "success", "tenant": tenant})@console_ns.route("/workspaces/current/permission")@@ -447,24 +327,7 @@ class WorkspacePermissionApi(Resource):"""Get workspace permissions for the current workspace."""@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[WorkspacePermissionResponse.__name__])- @setup_required- @login_required- @account_initialization_required- @only_edition_enterprise- @with_current_tenant_id- def get(self, current_tenant_id: str):- """- Get workspace permission settings.- Returns permission flags that control workspace features like member invitations and owner transfer.- """- if not current_tenant_id:- raise ValueError("No current tenant")-- # Get workspace permissions from enterprise service- permission = EnterpriseService.WorkspacePermissionService.get_permission(current_tenant_id)-- return WorkspacePermissionResponse(- workspace_id=permission.workspace_id,- allow_member_invite=permission.allow_member_invite,- allow_owner_transfer=permission.allow_owner_transfer,- ).model_dump(mode="json"), HTTPStatus.OK+ @console_account_admission(editions=frozenset({DeploymentEdition.ENTERPRISE}))+ def get(self, context: RequestContext):+ permission = application_services().workspaces.management.permission(context)+ return dump_response(WorkspacePermissionResponse, permission), HTTPStatus.OKdiff --git a/api/controllers/inner_api/agent/files.py b/api/controllers/inner_api/agent/files.pyindex d4e224622f7..66a08d9e445 100644--- a/api/controllers/inner_api/agent/files.py+++ b/api/controllers/inner_api/agent/files.py@@ -17,9 +17,9 @@ from controllers.inner_api.plugin.wraps import get_userfrom controllers.inner_api.wraps import plugin_inner_api_onlyfrom core.plugin.entities.request import RequestDownloadFileMapping, RequestRequestUploadFilefrom core.tools.signature import bind_file_uri, get_signed_file_uri_for_plugin+from extensions.ext_application_services import application_servicesfrom fields.base import ResponseModelfrom libs.exception import BaseHTTPException-from services.account_service import TenantServicefrom services.file_request_service import FileRequestService@@ -107,7 +107,7 @@ class AgentFileUploadRequestApi(Resource):status_code=400,) from exc- tenant = TenantService.get_tenant_by_id(payload.tenant_id, session=session)+ tenant = application_services().workspaces.management.get(payload.tenant_id)if tenant is None:raise AgentFileRequestHttpError(error_code="tenant_not_found",@@ -116,7 +116,7 @@ class AgentFileUploadRequestApi(Resource):)try:if payload.user_from == "account":- if not TenantService.account_belongs_to_tenant(payload.user_id, tenant.id, session=session):+ if not application_services().workspaces.members.get_role(tenant.id, payload.user_id):raise ValueError("account not found")owner_id = payload.user_idelse:@@ -164,7 +164,7 @@ class AgentFileDownloadRequestApi(Resource):status_code=400,) from exc- if TenantService.get_tenant_by_id(payload.tenant_id, session=session) is None:+ if application_services().workspaces.management.get(payload.tenant_id) is None:raise AgentFileRequestHttpError(error_code="tenant_not_found",description="tenant not found",diff --git a/api/controllers/inner_api/workspace/workspace.py b/api/controllers/inner_api/workspace/workspace.pyindex b1d5f82ed9b..1414eefe279 100644--- a/api/controllers/inner_api/workspace/workspace.py+++ b/api/controllers/inner_api/workspace/workspace.py@@ -1,21 +1,19 @@-import json-from flask_restx import Resourcefrom pydantic import BaseModel-from sqlalchemy import select+from controllers.common.errors import InvalidArgumentErrorfrom controllers.common.schema import register_schema_models-from controllers.console.wraps import model_validate, setup_required+from controllers.console.wraps import setup_required, validate_requestfrom controllers.inner_api import inner_api_ns-from controllers.inner_api.wraps import enterprise_inner_api_only-from events.tenant_event import tenant_was_created-from extensions.ext_database import db-from models import Account-from models.account import TenantAccountRole-from services.account_service import (- EnterpriseWorkspaceMemberAccountNotFoundError,- EnterpriseWorkspaceMemberWorkspaceNotFoundError,- TenantService,+from controllers.inner_api.wraps import inner_api_only+from enums.account import TenantAccountRole+from extensions.ext_application_services import application_services+from services.account_errors import AccountNotFoundError+from services.errors.workspace import (+ InvalidWorkspaceMemberRoleError,+ WorkspaceNotFoundError,+ WorkspaceOwnerNotFoundError,+ WorkspacesLimitExceededError,)@@ -43,7 +41,7 @@ register_schema_models(inner_api_ns, WorkspaceCreatePayload, WorkspaceOwnerlessP@inner_api_ns.route("/enterprise/workspace")class EnterpriseWorkspace(Resource):@setup_required- @enterprise_inner_api_only+ @inner_api_only@inner_api_ns.doc("create_enterprise_workspace")@inner_api_ns.doc(description="Create a new enterprise workspace with owner assignment")@inner_api_ns.expect(inner_api_ns.models[WorkspaceCreatePayload.__name__])@@ -54,38 +52,31 @@ class EnterpriseWorkspace(Resource):404: "Owner account not found or service not available",})- @model_validate(WorkspaceCreatePayload)- def post(self, args: WorkspaceCreatePayload):- account = db.session.scalar(select(Account).where(Account.email == args.owner_email).limit(1))- if account is None:+ def post(self):+ args = validate_request(WorkspaceCreatePayload)+ try:+ tenant = application_services().workspaces.provisioning.create(name=args.name, owner_email=args.owner_email)+ except WorkspaceOwnerNotFoundError:return {"message": "owner account not found."}, 404-- tenant = TenantService.create_owner_tenant(- account,- name=args.name,- is_from_dashboard=True,- session=db.session(),- )-- resp = {- "id": tenant.id,- "name": tenant.name,- "plan": tenant.plan,- "status": tenant.status,- "created_at": tenant.created_at.isoformat() + "Z" if tenant.created_at else None,- "updated_at": tenant.updated_at.isoformat() + "Z" if tenant.updated_at else None,- }-+ except WorkspacesLimitExceededError as exc:+ raise InvalidArgumentError(str(exc)) from excreturn {"message": "enterprise workspace created.",- "tenant": resp,+ "tenant": {+ "id": tenant.id,+ "name": tenant.name,+ "plan": tenant.plan,+ "status": tenant.status,+ "created_at": tenant.created_at.isoformat() + "Z" if tenant.created_at else None,+ "updated_at": tenant.updated_at.isoformat() + "Z" if tenant.updated_at else None,+ },}@inner_api_ns.route("/enterprise/workspace/ownerless")class EnterpriseWorkspaceNoOwnerEmail(Resource):@setup_required- @enterprise_inner_api_only+ @inner_api_only@inner_api_ns.doc("create_enterprise_workspace_ownerless")@inner_api_ns.doc(description="Create a new enterprise workspace without initial owner assignment")@inner_api_ns.expect(inner_api_ns.models[WorkspaceOwnerlessPayload.__name__])@@ -96,33 +87,28 @@ class EnterpriseWorkspaceNoOwnerEmail(Resource):404: "Service not available",})- @model_validate(WorkspaceOwnerlessPayload)- def post(self, args: WorkspaceOwnerlessPayload):- tenant = TenantService.create_tenant(args.name, is_from_dashboard=True, session=db.session())-- tenant_was_created.send(tenant)-- resp = {- "id": tenant.id,- "name": tenant.name,- "encrypt_public_key": tenant.encrypt_public_key,- "plan": tenant.plan,- "status": tenant.status,- "custom_config": json.loads(tenant.custom_config) if tenant.custom_config else {},- "created_at": tenant.created_at.isoformat() + "Z" if tenant.created_at else None,- "updated_at": tenant.updated_at.isoformat() + "Z" if tenant.updated_at else None,- }-+ def post(self):+ args = validate_request(WorkspaceOwnerlessPayload)+ tenant = application_services().workspaces.provisioning.create(name=args.name)return {"message": "enterprise workspace created.",- "tenant": resp,+ "tenant": {+ "id": tenant.id,+ "name": tenant.name,+ "encrypt_public_key": tenant.encrypt_public_key,+ "plan": tenant.plan,+ "status": tenant.status,+ "custom_config": tenant.custom_config,+ "created_at": tenant.created_at.isoformat() + "Z" if tenant.created_at else None,+ "updated_at": tenant.updated_at.isoformat() + "Z" if tenant.updated_at else None,+ },}@inner_api_ns.route("/enterprise/workspace/member")class EnterpriseWorkspaceMember(Resource):@setup_required- @enterprise_inner_api_only+ @inner_api_only@inner_api_ns.doc("join_enterprise_workspace_member")@inner_api_ns.doc(description="Add an existing account to an enterprise workspace")@inner_api_ns.expect(inner_api_ns.models[WorkspaceMemberPayload.__name__])@@ -134,33 +120,27 @@ class EnterpriseWorkspaceMember(Resource):404: "Workspace or account not found",})- @model_validate(WorkspaceMemberPayload)- def post(self, args: WorkspaceMemberPayload):+ def post(self):+ args = validate_request(WorkspaceMemberPayload)try:- role = TenantAccountRole(args.role)- except ValueError:- return {"message": "invalid workspace member role."}, 400- if role == TenantAccountRole.OWNER:- return {"message": "cannot join workspace as owner."}, 400-- try:- membership = TenantService.join_enterprise_workspace_member(+ member = application_services().workspaces.provisioning.join_member(workspace_id=args.workspace_id,account_id=args.account_id,email=args.email,- role=role,+ role=args.role,operator_account_id=args.operator_account_id,)- except EnterpriseWorkspaceMemberWorkspaceNotFoundError:+ except InvalidWorkspaceMemberRoleError as exc:+ return {"message": str(exc)}, 400+ except WorkspaceNotFoundError:return {"message": "workspace not found."}, 404- except EnterpriseWorkspaceMemberAccountNotFoundError:+ except AccountNotFoundError:return {"message": "account not found."}, 404-return {"message": "enterprise workspace member joined.","member": {- "workspace_id": membership.tenant_id,- "account_id": membership.account_id,- "role": membership.role.value,+ "workspace_id": member.workspace_id,+ "account_id": member.account_id,+ "role": member.role,},}diff --git a/api/controllers/openapi/app_dsl.py b/api/controllers/openapi/app_dsl.pyindex 2be74f15fc0..a6b581b7c3b 100644--- a/api/controllers/openapi/app_dsl.py+++ b/api/controllers/openapi/app_dsl.py@@ -33,8 +33,8 @@ from machinery.context import RequestContextfrom models.account import TenantAccountRolefrom services.app_dsl_service import AppDslServicefrom services.entities.dsl_entities import AppImportParams, CheckDependenciesResult, Import, ImportStatus-from services.errors.account import NoPermissionErrorfrom services.errors.app import WorkflowNotFoundError+from services.errors.base import NoPermissionErrordef _import_response(result: Import, *, workspace_id: str) -> AppDslImportResponse:diff --git a/api/controllers/openapi/apps.py b/api/controllers/openapi/apps.pyindex 531971a98cc..e8e10edcac2 100644--- a/api/controllers/openapi/apps.py+++ b/api/controllers/openapi/apps.py@@ -40,7 +40,6 @@ from extensions.ext_application_services import application_servicesfrom models import Appfrom models.enums import AppStatusfrom models.model import AppMode-from services.account_service import TenantServicefrom services.app.access import AppAccessFilter, resolve_app_access_filterfrom services.entities.app_entities import AppListParams, AppSummary@@ -184,7 +183,8 @@ class AppListApi(Resource):str(app.id), str(app.maintainer) if app.maintainer else None, account_id):return empty- tenant_name = TenantService.get_tenant_name(workspace_id, session=ctx.session)+ workspace = application_services().workspaces.management.get(workspace_id)+ tenant_name = workspace.name if workspace else Noneitem = AppListRow(id=str(app.id),name=app.name,@@ -216,7 +216,8 @@ class AppListApi(Resource):tenant_name = Noneif pagination.items:- tenant_name = TenantService.get_tenant_name(workspace_id, session=ctx.session)+ workspace = application_services().workspaces.management.get(workspace_id)+ tenant_name = workspace.name if workspace else Noneitems = [AppListRow(diff --git a/api/controllers/openapi/apps_permitted_external.py b/api/controllers/openapi/apps_permitted_external.pyindex 3c9f8c581eb..54586772b5f 100644--- a/api/controllers/openapi/apps_permitted_external.py+++ b/api/controllers/openapi/apps_permitted_external.py@@ -33,7 +33,6 @@ from controllers.openapi.auth.subjects import ExternalSsoSubjectfrom enums import DeploymentEditionfrom extensions.ext_application_services import application_servicesfrom models.enums import AppStatus-from services.account_service import TenantServicefrom services.enterprise.app_permitted_service import list_permitted_appsfrom services.entities.app_entities import AppSummary@@ -73,7 +72,7 @@ class PermittedExternalAppsListApi(Resource):str(a.id): a for a in application_services().apps.queries.find_visible_apps_by_ids(page_result.app_ids)}tenant_ids = list({str(a.tenant_id) for a in apps_by_id.values()})- tenants_by_id = {str(t.id): t for t in TenantService.get_tenants_by_ids(tenant_ids, session=ctx.session)}+ tenants_by_id = {str(t.id): t for t in application_services().workspaces.management.get_many(tenant_ids)}items: list[AppListRow] = []for app_id in page_result.app_ids:diff --git a/api/controllers/openapi/auth/context.py b/api/controllers/openapi/auth/context.pyindex 5b44d23d761..d78c1d742b8 100644--- a/api/controllers/openapi/auth/context.py+++ b/api/controllers/openapi/auth/context.py@@ -17,6 +17,8 @@ from typing import TYPE_CHECKINGfrom sqlalchemy.orm import Session+from core.logging.context import get_request_id, get_trace_id+from machinery.context import RequestContextfrom models.account import Account, Tenant, TenantAccountRolefrom models.model import App, EndUser@@ -39,11 +41,23 @@ class Context:subject: Subjectsession: Sessionview_args: Mapping[str, str]+ request_id: str = field(default_factory=get_request_id)+ trace_id: str | None = field(default_factory=get_trace_id)_app: App | None = field(default=None, init=False)_workspace: Tenant | None = field(default=None, init=False)_workspace_role: TenantAccountRole | None = field(default=None, init=False)_caller: Caller | None = field(default=None, init=False)+ @property+ def request_context(self) -> RequestContext:+ """Pass only stable identity values across the application boundary."""+ return RequestContext(+ request_id=self.request_id,+ trace_id=self.trace_id,+ account_id=str(self.subject.account_id),+ active_workspace_id=str(self.workspace.id),+ )+@propertydef app(self) -> App:return _loaded(self._app, "app")diff --git a/api/controllers/openapi/auth/loaders.py b/api/controllers/openapi/auth/loaders.pyindex ac91c35fc4a..7a357ffc3f8 100644--- a/api/controllers/openapi/auth/loaders.py+++ b/api/controllers/openapi/auth/loaders.py@@ -7,10 +7,10 @@ from flask import requestfrom werkzeug.exceptions import Forbidden, NotFoundfrom controllers.openapi.auth.context import Caller, Context, RouteContractError+from extensions.ext_application_services import application_servicesfrom models.account import Account, AccountStatus, Tenant, TenantAccountRole, TenantStatusfrom models.enums import AppStatusfrom models.model import App, EndUser-from services.account_service import TenantServicefrom services.app_service import AppService@@ -106,7 +106,7 @@ def _fetch_workspace(ctx: Context) -> Tenant:def _workspace_from_app(ctx: Context) -> Tenant:app = load_app(ctx)- tenant = TenantService.get_tenant_by_id(app.tenant_id, session=ctx.session)+ tenant = application_services().workspaces.identity.get_workspace(str(app.tenant_id))if tenant is None or tenant.status == TenantStatus.ARCHIVE:raise Forbidden("workspace unavailable")return tenant@@ -120,7 +120,7 @@ def _workspace_from_request(ctx: Context) -> Tenant:uuid.UUID(workspace_id)except ValueError:raise NotFound("workspace not found")- tenant = TenantService.get_tenant_by_id(workspace_id, session=ctx.session)+ tenant = application_services().workspaces.identity.get_workspace(workspace_id)if tenant is None or tenant.status == TenantStatus.ARCHIVE:raise NotFound("workspace not found")return tenant@@ -131,7 +131,7 @@ def _fetch_workspace_role(ctx: Context) -> TenantAccountRole:caller = load_caller(ctx)if not isinstance(caller, Account) or caller.status != AccountStatus.ACTIVE:raise NotFound("workspace not found")- role = TenantService.get_account_role_in_tenant(str(ctx.subject.account_id), workspace.id, session=ctx.session)+ role = application_services().workspaces.members.get_role(str(workspace.id), str(ctx.subject.account_id))if role is None:raise NotFound("workspace not found")return rolediff --git a/api/controllers/openapi/auth/requirements.py b/api/controllers/openapi/auth/requirements.pyindex d78b771e68d..20cd0612cad 100644--- a/api/controllers/openapi/auth/requirements.py+++ b/api/controllers/openapi/auth/requirements.py@@ -21,14 +21,17 @@ from configs import dify_configfrom constants.oauth_bearer import Scopefrom controllers.common.rbac import RBACCheck, enforce_rbac_checksfrom controllers.openapi._audit import emit_wrong_surface+from controllers.openapi._errors import MemberLicenseExceeded, MemberLimitExceededfrom controllers.openapi.auth.context import Contextfrom controllers.openapi.auth.loaders import load_app, load_caller, load_workspace, load_workspace_rolefrom controllers.openapi.auth.subjects import Subjectfrom enums import DeploymentEdition+from extensions.ext_application_services import application_servicesfrom models.account import TenantAccountRolefrom models.enums import CreatorUserRolefrom services.enterprise.enterprise_service import EnterpriseService, WebAppAccessModefrom services.entities.feature_entities import LicenseStatus+from services.errors.workspace import WorkspaceInvitationQuotaError, WorkspaceMemberLicenseQuotaErrorfrom services.system_feature_service import SystemFeatureService_DEAD_LICENSE_STATUSES = frozenset({LicenseStatus.INACTIVE, LicenseStatus.EXPIRED, LicenseStatus.LOST})@@ -116,6 +119,19 @@ class CheckScope(Requirement):raise Forbidden("insufficient_scope")+class CheckWorkspaceInvitationQuota(Requirement):+ """Run after workspace membership and permission checks, before the handler."""++ @override+ def run(self, subject: Subject, ctx: Context, session: Session) -> None:+ try:+ application_services().workspaces.invitations.check_invitation_quota(ctx.request_context)+ except WorkspaceMemberLicenseQuotaError as error:+ raise MemberLicenseExceeded() from error+ except WorkspaceInvitationQuotaError as error:+ raise MemberLimitExceeded() from error++class CheckRBACPermission(Requirement):"""The same check bundles the console's `rbac_permission_required` takes.Inert wherever RBAC is off; a route that needs a check there declares adiff --git a/api/controllers/openapi/auth/router.py b/api/controllers/openapi/auth/router.pyindex b0a5fa396ef..f98600f3d94 100644--- a/api/controllers/openapi/auth/router.py+++ b/api/controllers/openapi/auth/router.py@@ -14,6 +14,7 @@ from controllers.openapi.auth.requirements import assert_license_validfrom controllers.openapi.auth.spec import EndpointSpecfrom controllers.openapi.auth.subjects import subject_from_authfrom core.db.session_factory import session_factory+from core.logging.context import get_trace_idfrom enums import DeploymentEditionfrom libs.oauth_bearer import InvalidBearerError, assert_bearer_feature_enabled, extract_bearer, get_authenticator@@ -61,7 +62,12 @@ class AuthRouter:# Account-context endpoints materialize identity and release it in the# pipeline, before calling services that own their transactions.with session_factory.create_session() as session:- ctx = Context(subject, session, dict(request.view_args or {}))+ ctx = Context(+ subject,+ session,+ dict(request.view_args or {}),+ trace_id=get_trace_id() or request.headers.get("X-Trace-Id"),+ )try:result = pipeline.run(subject=subject,diff --git a/api/controllers/openapi/auth/subjects.py b/api/controllers/openapi/auth/subjects.pyindex 39166cfc0fd..162993665f9 100644--- a/api/controllers/openapi/auth/subjects.py+++ b/api/controllers/openapi/auth/subjects.py@@ -21,7 +21,6 @@ from libs.oauth_bearer import AuthContextfrom models.account import Accountfrom models.enums import CreatorUserRole, EndUserTypefrom models.model import EndUser-from services.account_service import AccountServicefrom services.enterprise.enterprise_service import WebAppAccessMode_SUBJECT_CLASSES: dict[SubjectType, type[Subject]] = {}@@ -87,7 +86,7 @@ class AccountSubject(Subject):@overridedef resolve_caller(self, ctx: Context, session: Session) -> Account:- account = AccountService.get_account_by_id(str(self.account_id), session=session)+ account = application_services().accounts.identity.get_account_by_id(str(self.account_id))if account is None:raise Unauthorized("account not found")if ctx._workspace is not None:@@ -143,7 +142,7 @@ class ExternalSsoSubject(Subject):identity = self.external_identityif identity is None:return None- account = AccountService.get_account_by_email(identity.email, session=session)+ account = application_services().accounts.identity.get_account_by_email(identity.email)return account.id if account is not None else Nonediff --git a/api/controllers/openapi/workspaces.py b/api/controllers/openapi/workspaces.pyindex e1c010ef66a..78a96910fe8 100644--- a/api/controllers/openapi/workspaces.py+++ b/api/controllers/openapi/workspaces.py@@ -12,8 +12,8 @@ account bearer and lets the view's own membership-scoped lookup answer 404.from __future__ import annotations-from itertools import starmapfrom urllib import parse+from uuid import UUIDfrom flask_restx import Resourcefrom werkzeug.exceptions import BadRequest, NotFound@@ -23,7 +23,6 @@ from constants.oauth_bearer import Scopefrom controllers.common.rbac import RBACCheck, RBACPermission, Workspacefrom controllers.openapi import openapi_nsfrom controllers.openapi._contract import Example, Kind, endpoint-from controllers.openapi._errors import MemberLicenseExceeded, MemberLimitExceededfrom controllers.openapi._models import (MemberActionResponse,MemberInvitePayload,@@ -42,50 +41,37 @@ from controllers.openapi.auth.requirements import (CheckRBACPermission,CheckScope,CheckSubject,+ CheckWorkspaceInvitationQuota,CheckWorkspaceMember,CheckWorkspaceRole,)from controllers.openapi.auth.subjects import AccountSubject-from enums import DeploymentEdition-from models import Account, Tenant, TenantAccountJoin-from models.account import TenantAccountRole-from services.account_service import AccountService, RegisterService, TenantService-from services.errors.account import (+from enums.account import TenantAccountRole+from extensions.ext_application_services import application_services+from services.account_errors import AccountNotFoundError, AccountRegisterError, SeatsLimitExceededError+from services.errors.base import NoPermissionError+from services.errors.workspace import (AccountAlreadyInTenantError,- AccountNotLinkTenantError,- AccountRegisterError,CannotOperateSelfError,+ InvalidWorkspaceMemberRoleError,MemberNotInTenantError,- NoPermissionError,RoleAlreadyAssignedError,- SeatsLimitExceededError,+ WorkspaceNotLinkedError,)-from services.feature_service import FeatureService+from services.workspace.contracts import WorkspaceInvitation, WorkspaceMemberRecord, WorkspaceSnapshot-def _member_response(account: Account) -> MemberResponse:+def _member_response(account: WorkspaceMemberRecord) -> MemberResponse:return MemberResponse(id=account.id,name=account.name,email=account.email,- role=account.role.value if account.role else "",- status=account.status.value if account.status else "",+ role=account.legacy_role,+ status=account.status,avatar=account.avatar,)-def _check_member_invite_quota(tenant_id: str) -> None:- features = FeatureService.get_features(tenant_id)-- if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:- members = features.members- if 0 < members.limit <= members.size:- raise MemberLimitExceeded()-- if features.workspace_members.enabled and not features.workspace_members.is_available(1):- raise MemberLicenseExceeded()--@openapi_ns.route("/workspaces")class WorkspacesApi(Resource):@endpoint(@@ -98,8 +84,8 @@ class WorkspacesApi(Resource):returns=(200, WorkspaceListResponse, "Workspace list"),)def get(self, ctx: Context, *, query: WorkspaceListQuery):- rows = TenantService.get_workspaces_for_account(str(ctx.subject.account_id), session=ctx.session)- return WorkspaceListResponse.page_of(list(starmap(_workspace_summary, rows)), query=query)+ rows = application_services().workspaces.management.list_memberships(str(ctx.subject.account_id))+ return WorkspaceListResponse.page_of([_workspace_summary(row) for row in rows], query=query)@openapi_ns.route("/workspaces/<string:workspace_id>")@@ -116,12 +102,11 @@ class WorkspaceByIdApi(Resource):returns=(200, WorkspaceDetailResponse, "Workspace detail"),)def get(self, ctx: Context, workspace_id: str):- row = TenantService.find_workspace_for_account(str(ctx.subject.account_id), workspace_id, session=ctx.session)+ row = application_services().workspaces.management.find_membership(str(ctx.subject.account_id), workspace_id)if row is None:raise NotFound("workspace not found")- tenant, membership = row- return _workspace_detail(tenant, membership)+ return _workspace_detail(row)@openapi_ns.route("/workspaces/<string:workspace_id>:switch")@@ -148,15 +133,12 @@ class WorkspaceSwitchApi(Resource):)def post(self, ctx: Context, workspace_id: str):try:- TenantService.switch_tenant(ctx.account, workspace_id, session=ctx.session)- except AccountNotLinkTenantError:- raise NotFound("workspace not found")-- row = TenantService.find_workspace_for_account(str(ctx.subject.account_id), workspace_id, session=ctx.session)- if row is None:- raise NotFound("workspace not found")- tenant, membership = row- return _workspace_detail(tenant, membership)+ workspace = application_services().workspaces.management.switch_membership(+ str(ctx.subject.account_id), workspace_id+ )+ except WorkspaceNotLinkedError:+ raise NotFound("workspace not found") from None+ return _workspace_detail(workspace)@openapi_ns.route("/workspaces/<string:workspace_id>/members")@@ -181,8 +163,15 @@ class WorkspaceMembersApi(Resource):returns=(200, MemberListResponse, "Member list"),)def get(self, ctx: Context, workspace_id: str, *, query: MemberListQuery):- members = TenantService.get_tenant_members(ctx.workspace, session=ctx.session)- return MemberListResponse.page_of([_member_response(m) for m in members], query=query)+ result = application_services().workspaces.member_queries.list_page(+ ctx.request_context, page=query.page, limit=query.limit+ )+ return MemberListResponse.build(+ page=query.page,+ limit=query.limit,+ total=result.total,+ items=[_member_response(m) for m in result.members],+ )@endpoint(op="invite.workspace.member",@@ -198,26 +187,23 @@ class WorkspaceMembersApi(Resource):CheckWorkspaceMember(),CheckRBACPermission(RBACCheck(RBACPermission.WORKSPACE_MEMBER_MANAGE, Workspace())),CheckWorkspaceRole(frozenset({TenantAccountRole.OWNER, TenantAccountRole.ADMIN})),+ CheckWorkspaceInvitationQuota(),),body=MemberInvitePayload,returns=(201, MemberInviteResponse, "Member invited"),)def post(self, ctx: Context, workspace_id: str, *, body: MemberInvitePayload):- tenant = ctx.workspace-- _check_member_invite_quota(tenant.id)-try:- token = RegisterService.invite_new_member(- tenant=tenant,+ invitation = application_services().workspaces.invitations.invite(+ ctx.request_context,email=body.email,language=None,role=body.role,- inviter=ctx.account,- session=ctx.session,)except AccountAlreadyInTenantError as exc:raise BadRequest(str(exc))+ except InvalidWorkspaceMemberRoleError as exc:+ raise BadRequest(str(exc)) from excexcept NoPermissionError as exc:raise BadRequest(str(exc))except SeatsLimitExceededError:@@ -225,20 +211,7 @@ class WorkspaceMembersApi(Resource):except AccountRegisterError as exc:raise BadRequest(str(exc))- normalized_email = body.email.lower()- member = AccountService.get_account_by_email_with_case_fallback(normalized_email, session=ctx.session)- if member is None:- raise RuntimeError("invited member missing from DB after invite")-- encoded_email = parse.quote(normalized_email)- invite_url = f"{dify_config.CONSOLE_WEB_URL}/activate?email={encoded_email}&token={token}"- return MemberInviteResponse(- email=normalized_email,- role=body.role,- member_id=member.id,- invite_url=invite_url,- tenant_id=tenant.id,- )+ return _invitation_response(invitation)@openapi_ns.route("/workspaces/<string:workspace_id>/members/<string:member_id>")@@ -266,12 +239,11 @@ class WorkspaceMemberApi(Resource):returns=(200, MemberActionResponse, "Member removed"),)def delete(self, ctx: Context, workspace_id: str, member_id: str):- member = AccountService.get_account_by_id(member_id, session=ctx.session)- if member is None:- raise NotFound("member not found")-+ member_id = _parse_member_id(member_id)try:- TenantService.remove_member_from_tenant(ctx.workspace, member, ctx.account, session=ctx.session)+ application_services().workspaces.members.remove(workspace_id, member_id, str(ctx.subject.account_id))+ except AccountNotFoundError:+ raise NotFound("member not found") from Noneexcept CannotOperateSelfError as exc:raise BadRequest(str(exc))except NoPermissionError as exc:@@ -300,12 +272,13 @@ class WorkspaceMemberApi(Resource):returns=(200, MemberActionResponse, "Role updated"),)def patch(self, ctx: Context, workspace_id: str, member_id: str, *, body: MemberRoleUpdatePayload):- member = AccountService.get_account_by_id(member_id, session=ctx.session)- if member is None:- raise NotFound("member not found")-+ member_id = _parse_member_id(member_id)try:- TenantService.update_member_role(ctx.workspace, member, body.role, ctx.account, session=ctx.session)+ application_services().workspaces.members.update_role(+ workspace_id, member_id, body.role, str(ctx.subject.account_id)+ )+ except AccountNotFoundError:+ raise NotFound("member not found") from Noneexcept CannotOperateSelfError as exc:raise BadRequest(str(exc))except NoPermissionError as exc:@@ -314,26 +287,47 @@ class WorkspaceMemberApi(Resource):raise NotFound(str(exc))except RoleAlreadyAssignedError as exc:raise BadRequest(str(exc))+ except InvalidWorkspaceMemberRoleError as exc:+ raise BadRequest(str(exc)) from excreturn MemberActionResponse()-def _workspace_summary(tenant: Tenant, membership: TenantAccountJoin) -> WorkspaceSummaryResponse:+def _parse_member_id(member_id: str) -> str:+ # Permission comparisons must use the same identity as UUID database lookups.+ try:+ return str(UUID(member_id))+ except ValueError:+ raise NotFound("member not found") from None+++def _invitation_response(invitation: WorkspaceInvitation) -> MemberInviteResponse:+ encoded_email = parse.quote(invitation.email)+ return MemberInviteResponse(+ email=invitation.email,+ role=invitation.role,+ member_id=invitation.account_id,+ invite_url=f"{dify_config.CONSOLE_WEB_URL}/activate?email={encoded_email}&token={invitation.token}",+ tenant_id=invitation.workspace_id,+ )+++def _workspace_summary(tenant: WorkspaceSnapshot) -> WorkspaceSummaryResponse:return WorkspaceSummaryResponse(id=tenant.id,name=tenant.name,- role=getattr(membership, "role", ""),+ role=tenant.role or "",status=tenant.status,- current=getattr(membership, "current", False),+ current=tenant.current,)-def _workspace_detail(tenant: Tenant, membership: TenantAccountJoin) -> WorkspaceDetailResponse:+def _workspace_detail(tenant: WorkspaceSnapshot) -> WorkspaceDetailResponse:return WorkspaceDetailResponse(id=tenant.id,name=tenant.name,- role=getattr(membership, "role", ""),+ role=tenant.role or "",status=tenant.status,- current=getattr(membership, "current", False),+ current=tenant.current,created_at=tenant.created_at.isoformat() if tenant.created_at else None,)diff --git a/api/controllers/service_api/__init__.py b/api/controllers/service_api/__init__.pyindex 5b44247685b..3569bbea9b1 100644--- a/api/controllers/service_api/__init__.py+++ b/api/controllers/service_api/__init__.py@@ -1,6 +1,7 @@from flask import Blueprintfrom flask_restx import Namespace+from controllers.common.errors import register_permission_error_handlerfrom libs.external_api import ExternalApibp = Blueprint("service_api", __name__, url_prefix="/v1")@@ -12,6 +13,7 @@ api = ExternalApi(description="API for application services",register_default_root=False,)+register_permission_error_handler(api)service_api_ns = Namespace("service_api", description="Service operations", path="/")diff --git a/api/controllers/service_api/dataset/dataset.py b/api/controllers/service_api/dataset/dataset.pyindex 9c6a2d6750d..79cbdae4e49 100644--- a/api/controllers/service_api/dataset/dataset.py+++ b/api/controllers/service_api/dataset/dataset.py@@ -16,7 +16,7 @@ from pydantic import (from sqlalchemy.orm import Sessionfrom werkzeug.exceptions import Forbidden, NotFound-import services+import services.errors.basefrom configs import dify_configfrom controllers.common.fields import SimpleResultResponsefrom controllers.common.schema import (@@ -607,7 +607,7 @@ class DatasetApi(DatasetApiResource):raise NotFound("Dataset not found.")try:DatasetService.check_dataset_permission(dataset, current_user, session)- except services.errors.account.NoPermissionError as e:+ except services.errors.base.NoPermissionError as e:raise Forbidden(str(e))data = _dump_service_dataset_detail(load_dataset_detail(dataset, session=session))# check embedding setting@@ -720,7 +720,6 @@ class DatasetApi(DatasetApiResource):payload.partial_member_list,session=session,)-dataset = DatasetService.update_dataset(dataset_id_str, update_data, current_user, session=session)if dataset is None:@@ -865,7 +864,7 @@ class DocumentStatusApi(DatasetApiResource):# Check user's permissiontry:DatasetService.check_dataset_permission(dataset, current_user, session)- except services.errors.account.NoPermissionError as e:+ except services.errors.base.NoPermissionError as e:raise Forbidden(str(e))# Check dataset model settingdiff --git a/api/core/app/task_pipeline/message_cycle_manager.py b/api/core/app/task_pipeline/message_cycle_manager.pyindex 5c8fc6d7531..f1100d69ef2 100644--- a/api/core/app/task_pipeline/message_cycle_manager.py+++ b/api/core/app/task_pipeline/message_cycle_manager.py@@ -36,7 +36,6 @@ from extensions.ext_database import dbfrom extensions.ext_redis import redis_clientfrom models.enums import MessageFileBelongsTofrom models.model import App, AppMode, Conversation, MessageAnnotation, MessageFile-from services.account_service import AccountServicefrom services.annotation_service import AppAnnotationServicelogger = logging.getLogger(__name__)@@ -166,14 +165,14 @@ class MessageCycleManager::param event: event:return:"""- annotation = AppAnnotationService.get_annotation_by_id(event.message_annotation_id, session)- if annotation:- account = AccountService.get_account_by_id(annotation.account_id, session=session)+ reply = AppAnnotationService.get_annotation_reply_by_id(event.message_annotation_id, session)+ if reply:+ annotation, account_name = replyself._task_state.metadata.annotation_reply = AnnotationReply(id=annotation.id,account=AnnotationReplyAccount(id=annotation.account_id,- name=account.name if account else "Dify user",+ name=account_name if account_name is not None else "Dify user",),)diff --git a/api/core/rag/index_processor/index_processor.py b/api/core/rag/index_processor/index_processor.pyindex 2ab23ae3a82..311f929ae23 100644--- a/api/core/rag/index_processor/index_processor.py+++ b/api/core/rag/index_processor/index_processor.py@@ -10,20 +10,42 @@ from sqlalchemy import delete, func, select, updatefrom sqlalchemy.orm import Sessionfrom core.db.session_factory import session_factory-from core.rag.index_processor.constant.index_type import IndexTechniqueType-from core.rag.index_processor.index_processor_base import SummaryIndexSettingDict+from core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType+from core.rag.index_processor.index_processor_base import BaseIndexProcessor, SummaryIndexSettingDictfrom core.workflow.nodes.knowledge_index.exc import KnowledgeIndexNodeErrorfrom core.workflow.nodes.knowledge_index.protocols import IndexingResultDict, Preview, PreviewItem, QaPreviewfrom models.dataset import Dataset, Document, DocumentSegmentfrom models.enums import SegmentStatusfrom services.vector_space_admission_service import VectorSpaceAdmissionService-from .index_processor_factory import IndexProcessorFactoryfrom .processor.paragraph_index_processor import ParagraphIndexProcessor+from .processor.parent_child_index_processor import ParentChildIndexProcessor+from .processor.qa_index_processor import QAIndexProcessorlogger = logging.getLogger(__name__)+class IndexProcessorFactory:+ """Select the processor for a document's index structure."""++ def __init__(self, index_type: str | None):+ self._index_type = index_type++ def init_index_processor(self) -> BaseIndexProcessor:+ """Create a processor for a supported index type."""+ if not self._index_type:+ raise ValueError("Index type must be specified.")++ if self._index_type == IndexStructureType.PARAGRAPH_INDEX:+ return ParagraphIndexProcessor()+ elif self._index_type == IndexStructureType.QA_INDEX:+ return QAIndexProcessor()+ elif self._index_type == IndexStructureType.PARENT_CHILD_INDEX:+ return ParentChildIndexProcessor()+ else:+ raise ValueError(f"Index type {self._index_type} is not supported.")++class IndexProcessor:def format_preview(self, chunk_structure: str, chunks: Any) -> Preview:index_processor = IndexProcessorFactory(chunk_structure).init_index_processor()diff --git a/api/core/rag/index_processor/index_processor_factory.py b/api/core/rag/index_processor/index_processor_factory.pydeleted file mode 100644index ea6ab246993..00000000000--- a/api/core/rag/index_processor/index_processor_factory.py+++ /dev/null@@ -1,29 +0,0 @@-"""Abstract interface for document loader implementations."""--from core.rag.index_processor.constant.index_type import IndexStructureType-from core.rag.index_processor.index_processor_base import BaseIndexProcessor-from core.rag.index_processor.processor.paragraph_index_processor import ParagraphIndexProcessor-from core.rag.index_processor.processor.parent_child_index_processor import ParentChildIndexProcessor-from core.rag.index_processor.processor.qa_index_processor import QAIndexProcessor---class IndexProcessorFactory:- """IndexProcessorInit."""-- def __init__(self, index_type: str | None):- self._index_type = index_type-- def init_index_processor(self) -> BaseIndexProcessor:- """Init index processor."""-- if not self._index_type:- raise ValueError("Index type must be specified.")-- if self._index_type == IndexStructureType.PARAGRAPH_INDEX:- return ParagraphIndexProcessor()- elif self._index_type == IndexStructureType.QA_INDEX:- return QAIndexProcessor()- elif self._index_type == IndexStructureType.PARENT_CHILD_INDEX:- return ParentChildIndexProcessor()- else:- raise ValueError(f"Index type {self._index_type} is not supported.")diff --git a/api/core/rag/index_processor/processor/paragraph_index_processor.py b/api/core/rag/index_processor/processor/paragraph_index_processor.pyindex 2102fe966c6..589b15ca007 100644--- a/api/core/rag/index_processor/processor/paragraph_index_processor.py+++ b/api/core/rag/index_processor/processor/paragraph_index_processor.py@@ -30,6 +30,7 @@ from core.rag.index_processor.index_processor_base import BaseIndexProcessor, Sufrom core.rag.models.document import AttachmentDocument, Document, MultimodalGeneralStructureChunkfrom core.tools.utils.text_processing_utils import remove_leading_symbolsfrom core.workflow.file_reference import build_file_reference+from extensions.ext_login import load_accountfrom factories.file_factory import build_from_mappingfrom graphon.file import File, FileTransferMethod, FileType, file_managerfrom graphon.model_runtime.entities.llm_entities import LLMResult, LLMUsage@@ -46,7 +47,6 @@ from models import UploadFilefrom models.account import Accountfrom models.dataset import Dataset, DatasetProcessRule, DocumentSegment, SegmentAttachmentBindingfrom models.dataset import Document as DatasetDocument-from services.account_service import AccountServicefrom services.knowledge.summaries.adapters import SummaryIndexAdapterlogger = logging.getLogger(__name__)@@ -242,8 +242,7 @@ class ParagraphIndexProcessor(BaseIndexProcessor):all_multimodal_documents.append(file_document)doc.attachments = attachmentselse:- with session_factory.create_session() as account_session:- account = AccountService.load_user(document.created_by, account_session)+ account = load_account(document.created_by)if not account:raise ValueError("Invalid account")doc.attachments = self._get_content_files(diff --git a/api/core/rag/index_processor/processor/parent_child_index_processor.py b/api/core/rag/index_processor/processor/parent_child_index_processor.pyindex 0c98b401800..e21c3469d80 100644--- a/api/core/rag/index_processor/processor/parent_child_index_processor.py+++ b/api/core/rag/index_processor/processor/parent_child_index_processor.py@@ -23,12 +23,12 @@ from core.rag.index_processor.constant.doc_type import DocTypefrom core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueTypefrom core.rag.index_processor.index_processor_base import BaseIndexProcessor, SummaryIndexSettingDictfrom core.rag.models.document import AttachmentDocument, ChildDocument, Document, ParentChildStructureChunk+from extensions.ext_login import load_accountfrom libs import helperfrom models import Accountfrom models.dataset import ChildChunk, Dataset, DatasetProcessRule, DocumentSegmentfrom models.dataset import Document as DatasetDocumentfrom models.enums import ProcessRuleMode-from services.account_service import AccountServicefrom services.knowledge.summaries.adapters import SummaryIndexAdapterlogger = logging.getLogger(__name__)@@ -307,8 +307,7 @@ class ParentChildIndexProcessor(BaseIndexProcessor):attachments.append(file_document)doc.attachments = attachmentselse:- with session_factory.create_session() as account_session:- account = AccountService.load_user(document.created_by, account_session)+ account = load_account(document.created_by)if not account:raise ValueError("Invalid account")doc.attachments = self._get_content_files(diff --git a/api/enums/account.py b/api/enums/account.pynew file mode 100644index 00000000000..777ac98e69b--- /dev/null+++ b/api/enums/account.py@@ -0,0 +1,64 @@+"""Shared workspace membership roles, independent of persistence models."""++from enum import StrEnum+from typing import Optional+++class TenantAccountRole(StrEnum):+ OWNER = "owner"+ ADMIN = "admin"+ EDITOR = "editor"+ NORMAL = "normal"+ DATASET_OPERATOR = "dataset_operator"++ @staticmethod+ def is_valid_role(role: str) -> bool:+ if not role:+ return False+ return role in {+ TenantAccountRole.OWNER,+ TenantAccountRole.ADMIN,+ TenantAccountRole.EDITOR,+ TenantAccountRole.NORMAL,+ TenantAccountRole.DATASET_OPERATOR,+ }++ @staticmethod+ def is_privileged_role(role: Optional["TenantAccountRole"]) -> bool:+ if not role:+ return False+ return role in {TenantAccountRole.OWNER, TenantAccountRole.ADMIN}++ @staticmethod+ def is_admin_role(role: Optional["TenantAccountRole"]) -> bool:+ if not role:+ return False+ return role == TenantAccountRole.ADMIN++ @staticmethod+ def is_non_owner_role(role: Optional["TenantAccountRole"]) -> bool:+ if not role:+ return False+ return role in {+ TenantAccountRole.ADMIN,+ TenantAccountRole.EDITOR,+ TenantAccountRole.NORMAL,+ TenantAccountRole.DATASET_OPERATOR,+ }++ @staticmethod+ def is_editing_role(role: Optional["TenantAccountRole"]) -> bool:+ if not role:+ return False+ return role in {TenantAccountRole.OWNER, TenantAccountRole.ADMIN, TenantAccountRole.EDITOR}++ @staticmethod+ def is_dataset_edit_role(role: Optional["TenantAccountRole"]) -> bool:+ if not role:+ return False+ return role in {+ TenantAccountRole.OWNER,+ TenantAccountRole.ADMIN,+ TenantAccountRole.EDITOR,+ TenantAccountRole.DATASET_OPERATOR,+ }diff --git a/api/extensions/application_services/account.py b/api/extensions/application_services/account.pynew file mode 100644index 00000000000..5cf7ba6573c--- /dev/null+++ b/api/extensions/application_services/account.py@@ -0,0 +1,358 @@+"""Compose the account domain using shared account and workspace persistence."""++from dataclasses import dataclass+from functools import partial++from sqlalchemy.orm import Session, sessionmaker++from configs import dify_config+from constants.languages import languages+from enums import DeploymentEdition+from extensions.ext_redis import RedisClientWrapper+from libs.datetime_utils import naive_utc_now, utc_now+from libs.helper import RateLimiter+from libs.oauth import GitHubOAuth, GoogleOAuth+from libs.oauth_bearer import invalidate_oauth_token_cache+from repositories.account.repository import SQLAlchemyAccountRepository+from repositories.account_activation_repository import SQLAlchemyAccountActivationRepository+from repositories.account_integration_repository import SQLAlchemyAccountIntegrationRepository+from repositories.oauth_access_token_repository import SQLAlchemyOAuthAccessTokenRepository+from repositories.workspace.workspace_repository import WorkspaceRepository+from services.account.adapters import (+ AccountIdentityGateway,+ BillingAccountActivationEligibility,+ BillingAccountDeletionFeedbackGateway,+ BillingAccountEducationGateway,+ BillingAccountEmailPolicyGateway,+ BillingWorkspaceMembershipCache,+ CeleryAccountDeletionScheduler,+ CeleryAccountDeletionVerificationNotifier,+ CeleryChangeEmailNotificationGateway,+ DeploymentAccountLifecyclePolicy,+ DeploymentWorkspaceInvitePolicy,+ EnterpriseAccountDeletionSyncGateway,+ RateLimiterChangeEmailSendLimiter,+ RBACWorkspaceMemberAccessSync,+ RedisChangeEmailSecurityGateway,+ RedisInvitationTokenStore,+ SecureChangeEmailCodeGenerator,+ TokenManagerAccountDeletionVerificationGateway,+ TokenManagerChangeEmailTokenGateway,+)+from services.account.email_registration_adapters import (+ AccountLifecycleRegistrationGateway,+ BillingAccountRegistrationPolicyGateway,+ CeleryEmailRegistrationNotificationGateway,+ RateLimiterEmailRegistrationSendLimiter,+ RedisEmailRegistrationSecurityGateway,+ SecureEmailRegistrationCodeGenerator,+ TokenManagerEmailRegistrationTokenGateway,+)+from services.account.email_registration_service import AccountEmailRegistrationService+from services.account.forgot_password_adapters import (+ CeleryForgotPasswordNotificationGateway,+ RateLimiterForgotPasswordSendLimiter,+ RedisForgotPasswordSecurityGateway,+ RedisForgotPasswordTokenGateway,+ SecureForgotPasswordCodeGenerator,+ SystemFeatureServiceForgotPasswordRegistrationPolicy,+)+from services.account.forgot_password_service import AccountForgotPasswordService+from services.account.login_adapters import (+ AccountActivationConsoleAuthInvitationGateway,+ DeploymentConsoleAuthPolicyGateway,+ LoggingConsoleAuthAuditGateway,+ RedisAccountSessionGateway,+ RedisConsoleAuthSecurityGateway,+ RedisEmailCodeGateway,+ RedisResetPasswordEmailGateway,+ SQLAlchemyAccountRefreshPreparationGateway,+ TurnstileHumanVerificationGateway,+)+from services.account.login_service import ConsoleAuthenticationService+from services.account.oauth_adapters import (+ AccountActivationOAuthInvitationGateway,+ AccountLifecycleOAuthRegistrationGateway,+ AccountLifecycleOAuthSessionGateway,+ DeploymentOAuthPolicyGateway,+ DifyOAuthProviderGateway,+ RedisOAuthAccountClaimLock,+ WorkspaceProvisioningOAuthGateway,+)+from services.account.oauth_service import AccountOAuthService, OAuthProviderGateway+from services.account.service import AccountService+from services.account_access_service import AccountAccessService+from services.account_activation_service import (+ AccountActivationRepository,+ AccountActivationService,+ InvitationTokenStore,+)+from services.account_avatar_file_gateway import SQLAlchemyAccountAvatarFileGateway+from services.account_avatar_service import AccountAvatarService+from services.account_change_email_service import AccountChangeEmailService+from services.account_deletion_feedback_service import AccountDeletionFeedbackService+from services.account_deletion_service import AccountDeletionService+from services.account_education_service import AccountEducationService+from services.account_initialization_service import AccountInitializationService+from services.account_integration_service import AccountIntegrationService+from services.account_password_hasher import DefaultAccountPasswordHasher+from services.account_password_service import AccountPasswordService+from services.account_profile_service import AccountProfileService+from services.workspace.provisioning_service import WorkspaceProvisioningService+++@dataclass(frozen=True, slots=True)+class AccountServices:+ access: AccountAccessService+ activation: AccountActivationService+ authentication: ConsoleAuthenticationService+ avatar: AccountAvatarService+ change_email: AccountChangeEmailService+ email_registration: AccountEmailRegistrationService+ deletion: AccountDeletionService+ deletion_feedback: AccountDeletionFeedbackService+ education: AccountEducationService+ forgot_password: AccountForgotPasswordService+ initialization: AccountInitializationService+ integrations: AccountIntegrationService+ oauth: AccountOAuthService+ password: AccountPasswordService+ profile: AccountProfileService+ lifecycle: AccountService+ identity: AccountIdentityGateway+++def _build_account_oauth_service(+ *,+ deployment_edition: DeploymentEdition,+ redis: RedisClientWrapper,+ accounts: SQLAlchemyAccountRepository,+ integrations: SQLAlchemyAccountIntegrationRepository,+ memberships: WorkspaceRepository,+ lifecycle: AccountService,+ workspace_provisioning: WorkspaceProvisioningService,+ invitation_tokens: InvitationTokenStore,+ activation_accounts: AccountActivationRepository,+) -> AccountOAuthService:+ providers: dict[str, OAuthProviderGateway] = {}+ if dify_config.GITHUB_CLIENT_ID and dify_config.GITHUB_CLIENT_SECRET:+ providers["github"] = DifyOAuthProviderGateway(+ provider_name="github",+ client=GitHubOAuth(+ client_id=dify_config.GITHUB_CLIENT_ID,+ client_secret=dify_config.GITHUB_CLIENT_SECRET,+ redirect_uri=dify_config.CONSOLE_API_URL + "/console/api/oauth/authorize/github",+ ),+ )+ if dify_config.GOOGLE_CLIENT_ID and dify_config.GOOGLE_CLIENT_SECRET:+ providers["google"] = DifyOAuthProviderGateway(+ provider_name="google",+ client=GoogleOAuth(+ client_id=dify_config.GOOGLE_CLIENT_ID,+ client_secret=dify_config.GOOGLE_CLIENT_SECRET,+ redirect_uri=dify_config.CONSOLE_API_URL + "/console/api/oauth/authorize/google",+ ),+ )++ policy = DeploymentOAuthPolicyGateway(+ billing_enabled=deployment_edition == DeploymentEdition.CLOUD,+ )+ return AccountOAuthService(+ providers=providers,+ accounts=accounts,+ integrations=integrations,+ memberships=memberships,+ invitations=AccountActivationOAuthInvitationGateway(tokens=invitation_tokens, accounts=activation_accounts),+ account_claims=RedisOAuthAccountClaimLock(client=redis),+ registration=AccountLifecycleOAuthRegistrationGateway(accounts=lifecycle),+ workspaces=WorkspaceProvisioningOAuthGateway(workspaces=workspace_provisioning),+ sessions=AccountLifecycleOAuthSessionGateway(accounts=lifecycle),+ registration_policy=policy,+ workspace_policy=policy,+ supported_languages=languages,+ now=naive_utc_now,+ )+++def build_account_services(+ *,+ database_client: sessionmaker[Session],+ deployment_edition: DeploymentEdition,+ redis: RedisClientWrapper,+ accounts: SQLAlchemyAccountRepository,+ integrations: SQLAlchemyAccountIntegrationRepository,+ workspace_repository: WorkspaceRepository,+ workspace_provisioning: WorkspaceProvisioningService,+ passwords: DefaultAccountPasswordHasher,+ invitation_tokens: RedisInvitationTokenStore,+ activation_accounts: SQLAlchemyAccountActivationRepository,+) -> AccountServices:+ lifecycle = AccountService(+ security=RedisConsoleAuthSecurityGateway(redis=redis),+ accounts=accounts,+ policies=DeploymentAccountLifecyclePolicy(),+ passwords=passwords,+ workspaces=workspace_provisioning,+ sessions=RedisAccountSessionGateway(redis=redis),+ now=naive_utc_now,+ )+ return AccountServices(+ lifecycle=lifecycle,+ activation=AccountActivationService(+ tokens=invitation_tokens,+ accounts=activation_accounts,+ workspace_policy=DeploymentWorkspaceInvitePolicy(),+ eligibility=BillingAccountActivationEligibility(+ enabled=deployment_edition == DeploymentEdition.CLOUD,+ ),+ membership_cache=BillingWorkspaceMembershipCache(+ enabled=deployment_edition == DeploymentEdition.CLOUD,+ ),+ member_access_sync=RBACWorkspaceMemberAccessSync(+ enabled=dify_config.RBAC_ENABLED,+ ),+ ),+ identity=AccountIdentityGateway(accounts=accounts, redis=redis),+ access=AccountAccessService(+ accounts=accounts,+ workspaces=workspace_repository,+ sessions=SQLAlchemyOAuthAccessTokenRepository(session_factory=database_client),+ invalidate_token_cache=partial(invalidate_oauth_token_cache, redis),+ now=utc_now,+ ),+ authentication=ConsoleAuthenticationService(+ accounts=accounts,+ workspaces=workspace_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(accounts=accounts),+ account_provisioning=workspace_provisioning,+ workspace_provisioning=workspace_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),+ ),+ change_email=AccountChangeEmailService(+ accounts=accounts,+ tokens=TokenManagerChangeEmailTokenGateway(),+ codes=SecureChangeEmailCodeGenerator(),+ notifications=CeleryChangeEmailNotificationGateway(),+ send_limits=RateLimiterChangeEmailSendLimiter(redis=redis),+ security=RedisChangeEmailSecurityGateway(+ redis=redis,+ email_send_ip_limit_per_minute=dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE,+ verification_failure_limit=5,+ verification_lockout_duration=dify_config.CHANGE_EMAIL_LOCKOUT_DURATION,+ ),+ email_policy=BillingAccountEmailPolicyGateway(+ billing_enabled=deployment_edition == DeploymentEdition.CLOUD,+ ),+ ),+ email_registration=AccountEmailRegistrationService(+ accounts=accounts,+ tokens=TokenManagerEmailRegistrationTokenGateway(),+ codes=SecureEmailRegistrationCodeGenerator(),+ notifications=CeleryEmailRegistrationNotificationGateway(),+ send_limits=RateLimiterEmailRegistrationSendLimiter(+ rate_limiter=RateLimiter(+ prefix="email_register_rate_limit",+ max_attempts=1,+ time_window=60,+ redis_client=redis,+ )+ ),+ security=RedisEmailRegistrationSecurityGateway(+ redis=redis,+ login_security=RedisConsoleAuthSecurityGateway(redis=redis),+ verification_failure_limit=5,+ verification_lockout_duration=dify_config.EMAIL_REGISTER_LOCKOUT_DURATION,+ ),+ account_policy=BillingAccountRegistrationPolicyGateway(+ enabled=deployment_edition == DeploymentEdition.CLOUD,+ ),+ registration=AccountLifecycleRegistrationGateway(accounts=lifecycle),+ ),+ deletion=AccountDeletionService(+ accounts=accounts,+ memberships=workspace_repository,+ verification=TokenManagerAccountDeletionVerificationGateway(),+ notifications=CeleryAccountDeletionVerificationNotifier(redis=redis),+ synchronization=EnterpriseAccountDeletionSyncGateway(),+ scheduler=CeleryAccountDeletionScheduler(),+ ),+ deletion_feedback=AccountDeletionFeedbackService(+ feedback=BillingAccountDeletionFeedbackGateway(),+ ),+ education=AccountEducationService(+ accounts=accounts,+ education=BillingAccountEducationGateway(),+ verification_rate_limiter=RateLimiter(+ prefix="edu_verification_rate_limit",+ max_attempts=10,+ time_window=60,+ redis_client=redis,+ ),+ activation_rate_limiter=RateLimiter(+ prefix="edu_activation_rate_limit",+ max_attempts=10,+ time_window=60,+ redis_client=redis,+ ),+ ),+ forgot_password=AccountForgotPasswordService(+ accounts=accounts,+ passwords=passwords,+ tokens=RedisForgotPasswordTokenGateway(+ redis=redis,+ expiry_seconds=dify_config.RESET_PASSWORD_TOKEN_EXPIRY_MINUTES * 60,+ ),+ codes=SecureForgotPasswordCodeGenerator(),+ notifications=CeleryForgotPasswordNotificationGateway(),+ send_limits=RateLimiterForgotPasswordSendLimiter(redis=redis),+ security=RedisForgotPasswordSecurityGateway(+ redis=redis,+ email_send_ip_limit_per_minute=dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE,+ verification_lockout_duration=dify_config.FORGOT_PASSWORD_LOCKOUT_DURATION,+ ),+ registration=SystemFeatureServiceForgotPasswordRegistrationPolicy(),+ ),+ initialization=AccountInitializationService(+ accounts=accounts,+ invitation_required=deployment_edition == DeploymentEdition.CLOUD,+ now=naive_utc_now,+ ),+ integrations=AccountIntegrationService(integrations=integrations),+ oauth=_build_account_oauth_service(+ deployment_edition=deployment_edition,+ redis=redis,+ accounts=accounts,+ integrations=integrations,+ memberships=workspace_repository,+ lifecycle=lifecycle,+ workspace_provisioning=workspace_provisioning,+ invitation_tokens=invitation_tokens,+ activation_accounts=activation_accounts,+ ),+ password=AccountPasswordService(+ accounts=accounts,+ passwords=passwords,+ ),+ profile=AccountProfileService(accounts=accounts),+ )diff --git a/api/extensions/application_services/app.py b/api/extensions/application_services/app.pyindex 31265ad1571..0ac0bc7edef 100644--- a/api/extensions/application_services/app.py+++ b/api/extensions/application_services/app.py@@ -4,7 +4,7 @@ from dataclasses import dataclassfrom sqlalchemy.orm import Session, sessionmaker-from repositories.account_repository import SQLAlchemyAccountRepository+from repositories.account.repository import SQLAlchemyAccountRepositoryfrom repositories.app.api_key_repository import AppApiKeyRepositoryfrom repositories.app.console_repository import ConsoleAppRepositoryfrom services.agent.roster_package_exporter import RosterAgentPackageExporterdiff --git a/api/extensions/application_services/workspace.py b/api/extensions/application_services/workspace.pynew file mode 100644index 00000000000..3a9f0b9b894--- /dev/null+++ b/api/extensions/application_services/workspace.py@@ -0,0 +1,107 @@+"""Compose workspace use cases with the shared account and workspace repositories."""++from dataclasses import dataclass++from sqlalchemy.orm import Session, sessionmaker++from extensions.ext_redis import RedisClientWrapper+from repositories.account.repository import SQLAlchemyAccountRepository+from repositories.workspace.workspace_repository import WorkspaceRepository+from services.account.adapters import RedisInvitationTokenStore+from services.file_service import FileService+from services.workspace.gateways import (+ DeploymentWorkspaceCreationPolicy,+ DeploymentWorkspaceFeatureGateway,+ DeploymentWorkspaceMemberAccessGateway,+ DeploymentWorkspaceMemberRoleResolver,+ DeploymentWorkspacePlanGateway,+ WorkspaceFileGateway,+ WorkspaceIdentityGateway,+ WorkspaceInvitationGateway,+ WorkspaceOwnerTransferGateway,+ WorkspaceProvisioningEffectsGateway,+)+from services.workspace.member_service import (+ InvitedAccountRegistration,+ WorkspaceInvitationService,+ WorkspaceMemberQueryService,+ WorkspaceMemberService,+ WorkspaceOwnerTransferService,+)+from services.workspace.provisioning_service import WorkspaceProvisioningService+from services.workspace.service import WorkspaceQueryService, WorkspaceService+++@dataclass(frozen=True, slots=True)+class WorkspaceServices:+ queries: WorkspaceQueryService+ management: WorkspaceService+ provisioning: WorkspaceProvisioningService+ members: WorkspaceMemberService+ member_queries: WorkspaceMemberQueryService+ owner_transfer: WorkspaceOwnerTransferService+ invitations: WorkspaceInvitationService+ identity: WorkspaceIdentityGateway+++def build_workspace_membership_services(+ *,+ database_client: sessionmaker[Session],+ workspaces: WorkspaceRepository,+ accounts: SQLAlchemyAccountRepository,+) -> tuple[WorkspaceMemberService, WorkspaceProvisioningService]:+ """Build the workspace prerequisites shared by account registration and invitations."""+ members = WorkspaceMemberService(+ workspaces=workspaces,+ accounts=accounts,+ access=DeploymentWorkspaceMemberAccessGateway(session_factory=database_client),+ )+ provisioning = WorkspaceProvisioningService(+ owners=accounts,+ provisioning=workspaces,+ effects=WorkspaceProvisioningEffectsGateway(session_factory=database_client),+ policies=DeploymentWorkspaceCreationPolicy(),+ memberships=workspaces,+ members=members,+ )+ return members, provisioning+++def build_workspace_services(+ *,+ workspaces: WorkspaceRepository,+ accounts: SQLAlchemyAccountRepository,+ files: FileService,+ redis: RedisClientWrapper,+ members: WorkspaceMemberService,+ provisioning: WorkspaceProvisioningService,+ registration: InvitedAccountRegistration,+ invitation_tokens: RedisInvitationTokenStore,+) -> WorkspaceServices:+ return WorkspaceServices(+ queries=WorkspaceQueryService(workspaces=workspaces, plans=DeploymentWorkspacePlanGateway()),+ management=WorkspaceService(+ workspaces=workspaces,+ features=DeploymentWorkspaceFeatureGateway(),+ logos=WorkspaceFileGateway(files=files),+ ),+ provisioning=provisioning,+ members=members,+ member_queries=WorkspaceMemberQueryService(+ members=workspaces,+ roles=DeploymentWorkspaceMemberRoleResolver(),+ ),+ owner_transfer=WorkspaceOwnerTransferService(+ accounts=accounts,+ workspaces=workspaces,+ members=members,+ challenges=WorkspaceOwnerTransferGateway(redis=redis),+ ),+ invitations=WorkspaceInvitationService(+ accounts=registration,+ workspaces=workspaces,+ members=members,+ invitations=WorkspaceInvitationGateway(tokens=invitation_tokens, redis=redis),+ ),+ identity=WorkspaceIdentityGateway(workspaces=workspaces),+ )diff --git a/api/extensions/ext_application_services.py b/api/extensions/ext_application_services.pyindex 6e43867eb65..cb36a69716f 100644--- a/api/extensions/ext_application_services.py+++ b/api/extensions/ext_application_services.py@@ -6,7 +6,6 @@ import timefrom collections.abc import Mapping, Sequencefrom dataclasses import dataclassfrom datetime import UTC, datetime-from functools import partialfrom typing import castfrom uuid import uuid4@@ -17,11 +16,11 @@ from sqlalchemy.orm import Session, sessionmakerfrom configs import dify_configfrom constants.dsl_version import CURRENT_APP_DSL_VERSION-from constants.languages import languagesfrom core.db.session_factory import get_session_makerfrom core.schemas.schema_manager import SchemaManagerfrom core.tools.tool_file_manager import ToolFileManagerfrom enums import DeploymentEdition, WebAppAccessMode+from extensions.application_services.account import AccountServices, build_account_servicesfrom extensions.application_services.agent import AgentAppServices, build_agent_app_servicesfrom extensions.application_services.app import AppServices, build_app_api_key_service, build_app_servicesfrom extensions.application_services.data_sources import (@@ -37,23 +36,19 @@ from extensions.application_services.knowledge import (build_knowledge_services,)from extensions.application_services.trial_app import TrialAppServices, build_trial_app_services+from extensions.application_services.workspace import (+ WorkspaceServices,+ build_workspace_membership_services,+ build_workspace_services,+)from extensions.ext_redis import RedisClientWrapper, redis_clientfrom extensions.ext_storage import storage-from libs.datetime_utils import naive_utc_now, utc_nowfrom libs.helper import RateLimiter-from libs.oauth import GitHubOAuth, GoogleOAuth-from libs.oauth_bearer import invalidate_oauth_token_cachefrom libs.passport import PassportServicefrom models.model import EndUser+from repositories.account.repository import SQLAlchemyAccountRepositoryfrom repositories.account_activation_repository import SQLAlchemyAccountActivationRepositoryfrom repositories.account_integration_repository import SQLAlchemyAccountIntegrationRepository-from repositories.account_oauth_repository import (- AccountServiceOAuthAccountRegistrationGateway,- AccountServiceOAuthSessionGateway,- AccountServiceOAuthWorkspaceGateway,- RegisterServiceOAuthInvitationGateway,-)-from repositories.account_repository import SQLAlchemyAccountRepositoryfrom repositories.app.mcp_server_repository import AppMCPServerRepositoryfrom repositories.app.site_command_repository import AppSiteCommandRepositoryfrom repositories.app.tracing_config_repository import SQLAlchemyAppTracingConfigRepository@@ -68,7 +63,6 @@ from repositories.file_grant_repository import FileGrantRepositoryfrom repositories.human_input_file_upload_repository import SQLAlchemyHumanInputFileUploadRepositoryfrom repositories.installation_state_repository import InstallationStateRepositoryfrom repositories.message_file_preview_repository import MessageFilePreviewQueryRepository-from repositories.oauth_access_token_repository import SQLAlchemyOAuthAccessTokenRepositoryfrom repositories.oauth_device_token_repository import SQLAlchemyOAuthDeviceTokenRepositoryfrom repositories.oauth_server_repository import RedisOAuthServerTokenRepository, SQLAlchemyOAuthServerRepositoryfrom repositories.plugin_file_upload_repository import SQLAlchemyPluginFileUploadOwnerRepository@@ -83,79 +77,20 @@ from repositories.web_passport_repository import WebPassportRepositoryfrom repositories.webapp_access_query_repository import WebAppAccessQueryRepositoryfrom repositories.workflow_app_log_query_repository import WorkflowAppLogQueryRepositoryfrom repositories.workflow_run_archive_repository import WorkflowRunArchiveBundleQueryRepository-from repositories.workspace_member_query_repository import WorkspaceMemberQueryRepository-from repositories.workspace_query_repository import WorkspaceQueryRepository-from services.account_access_service import AccountAccessService-from services.account_activation_service import AccountActivationService-from services.account_adapters import (- BillingAccountActivationEligibility,- BillingAccountDeletionFeedbackGateway,- BillingAccountEducationGateway,- BillingAccountEmailPolicyGateway,- BillingWorkspaceMembershipCache,- CeleryAccountDeletionScheduler,- CeleryAccountDeletionVerificationNotifier,- CeleryChangeEmailNotificationGateway,- DeploymentWorkspaceInvitePolicy,- EnterpriseAccountDeletionSyncGateway,- RateLimiterChangeEmailSendLimiter,- RBACWorkspaceMemberAccessSync,- RedisChangeEmailSecurityGateway,+from repositories.workspace.workspace_repository import WorkspaceRepository+from services.account.adapters import (+ InstallationTelemetryGateway,RedisInvitationTokenStore,- SecureChangeEmailCodeGenerator,- TokenManagerAccountDeletionVerificationGateway,- TokenManagerChangeEmailTokenGateway,-)-from services.account_avatar_file_gateway import SQLAlchemyAccountAvatarFileGateway-from services.account_avatar_service import AccountAvatarService-from services.account_change_email_service import AccountChangeEmailService-from services.account_deletion_feedback_service import AccountDeletionFeedbackService-from services.account_deletion_service import AccountDeletionService-from services.account_education_service import AccountEducationService-from services.account_email_registration_adapters import (- AccountServiceRegistrationGateway,- BillingAccountRegistrationPolicyGateway,- CeleryEmailRegistrationNotificationGateway,- RateLimiterEmailRegistrationSendLimiter,- RedisEmailRegistrationSecurityGateway,- SecureEmailRegistrationCodeGenerator,- TokenManagerEmailRegistrationTokenGateway,)-from services.account_email_registration_service import AccountEmailRegistrationService-from services.account_forgot_password_adapters import (- CeleryForgotPasswordNotificationGateway,- RateLimiterForgotPasswordSendLimiter,- RedisForgotPasswordSecurityGateway,- RedisForgotPasswordTokenGateway,- SecureForgotPasswordCodeGenerator,- SystemFeatureServiceForgotPasswordRegistrationPolicy,+from services.account.forgot_password_adapters import RedisForgotPasswordSecurityGateway+from services.account.forgot_password_service import (+ FORGOT_PASSWORD_SEND_RATE_LIMIT_MAX_ATTEMPTS,+ FORGOT_PASSWORD_SEND_RATE_LIMIT_PREFIX,+ FORGOT_PASSWORD_SEND_RATE_LIMIT_WINDOW_SECONDS,)-from services.account_forgot_password_service import AccountForgotPasswordService-from services.account_initialization_service import AccountInitializationService-from 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 ConsoleAuthenticationService-from services.account_oauth_adapters import (- DeploymentOAuthPolicyGateway,- DifyOAuthProviderGateway,- RedisOAuthAccountClaimLock,-)-from services.account_oauth_service import AccountOAuthService, OAuthProviderGateway+from services.account.login_adapters import RedisConsoleAuthSecurityGateway+from services.account.service import AccountSetupProvisionerfrom services.account_password_hasher import DefaultAccountPasswordHasher-from services.account_password_service import AccountPasswordService-from services.account_profile_service import AccountProfileService-from services.account_service import AccountServicefrom services.agent.roster_package_exporter import RosterAgentPackageExporterfrom services.app.advanced_prompt_template_service import AdvancedPromptTemplateServicefrom services.app.api_key_service import AppApiKeyService@@ -228,7 +163,7 @@ from services.retention.workflow_run.archive_download_task_cache import Workflowfrom services.retention.workflow_run.archive_log_service import WorkflowRunArchiveServicefrom services.saved_message_service import SavedMessageServicefrom services.schema_definition_service import SchemaDefinitionService-from services.setup_adapters import RedisSetupLock, RegisterServiceAccountProvisioner+from services.setup_adapters import RedisSetupLockfrom services.setup_service import SetupServicefrom services.step_by_step_tour_service import StepByStepTourServicefrom services.system_feature_service import SystemFeatureService@@ -237,7 +172,7 @@ from services.tool_file_download_service import ToolFileDownloadServicefrom services.upload_file_delivery_service import UploadFileDeliveryServicefrom services.web_app_runtime_query_service import WebAppRuntimeQueryServicefrom services.web_authentication_adapters import (- AccountServiceWebAuthenticationSecurityGateway,+ AccountWebAuthenticationSecurityGateway,LoggingWebAuthenticationAuditGateway,PassportWebAppSessionGateway,TokenManagerWebAuthenticationGateway,@@ -253,10 +188,6 @@ from services.webapp_access_query_service import WebAppAccessQueryService, WebApfrom services.workflow_app_log_query_service import WorkflowAppLogQueryServicefrom services.workflow_run_service import WorkflowRunServicefrom services.workflow_statistic_query_service import WorkflowStatisticQueryService-from services.workspace_member_query_service import WorkspaceMemberQueryService-from services.workspace_member_role_resolver import DeploymentWorkspaceMemberRoleResolver-from services.workspace_plan_gateway import DeploymentWorkspacePlanGateway-from services.workspace_query_service import WorkspaceQueryServicefrom tasks.mail_inner_task import enqueue_inner_maillogger = logging.getLogger(__name__)@@ -299,24 +230,6 @@ def _batch_get_enterprise_webapp_user_permissions(*, user_id: str, app_ids: Sequreturn {app_id: bool(allowed) for app_id, allowed in permissions.items()}-@dataclass(frozen=True, slots=True)-class AccountServices:- access: AccountAccessService- authentication: ConsoleAuthenticationService- avatar: AccountAvatarService- change_email: AccountChangeEmailService- email_registration: AccountEmailRegistrationService- deletion: AccountDeletionService- deletion_feedback: AccountDeletionFeedbackService- education: AccountEducationService- forgot_password: AccountForgotPasswordService- initialization: AccountInitializationService- integrations: AccountIntegrationService- oauth: AccountOAuthService- password: AccountPasswordService- profile: AccountProfileService--@dataclass(frozen=True, slots=True)class AppScopedEndUserServices:commands: AppScopedEndUserService[EndUser]@@ -331,7 +244,6 @@ class ApplicationServices:accounts: AccountServicesapp_api_keys: AppApiKeyServicedataset_api_keys: DatasetApiKeyService- account_activation: AccountActivationServiceapps: AppServicesapp_definitions: AppDefinitionQueryServiceapp_mcp_servers: AppMCPServerService@@ -376,8 +288,7 @@ class ApplicationServices:trial_apps: TrialAppServicesworkflow_run_archives: WorkflowRunArchiveServiceworkflow_runs: WorkflowRunService- workspace_queries: WorkspaceQueryService- workspace_member_queries: WorkspaceMemberQueryService+ workspaces: WorkspaceServicesworkflow_app_logs: WorkflowAppLogQueryServiceinner_mail: InnerMailServiceweb_passport: WebPassportService@@ -454,55 +365,6 @@ def _build_file_grant_service(*, database_client: sessionmaker[Session]) -> File)-def _build_account_oauth_service(- *,- database_client: sessionmaker[Session],- deployment_edition: DeploymentEdition,- redis: RedisClientWrapper,- accounts: SQLAlchemyAccountRepository,- integrations: SQLAlchemyAccountIntegrationRepository,- memberships: WorkspaceQueryRepository,-) -> AccountOAuthService:- providers: dict[str, OAuthProviderGateway] = {}- if dify_config.GITHUB_CLIENT_ID and dify_config.GITHUB_CLIENT_SECRET:- providers["github"] = DifyOAuthProviderGateway(- provider_name="github",- client=GitHubOAuth(- client_id=dify_config.GITHUB_CLIENT_ID,- client_secret=dify_config.GITHUB_CLIENT_SECRET,- redirect_uri=dify_config.CONSOLE_API_URL + "/console/api/oauth/authorize/github",- ),- )- if dify_config.GOOGLE_CLIENT_ID and dify_config.GOOGLE_CLIENT_SECRET:- providers["google"] = DifyOAuthProviderGateway(- provider_name="google",- client=GoogleOAuth(- client_id=dify_config.GOOGLE_CLIENT_ID,- client_secret=dify_config.GOOGLE_CLIENT_SECRET,- redirect_uri=dify_config.CONSOLE_API_URL + "/console/api/oauth/authorize/google",- ),- )-- policy = DeploymentOAuthPolicyGateway(- billing_enabled=deployment_edition == DeploymentEdition.CLOUD,- )- return AccountOAuthService(- providers=providers,- accounts=accounts,- integrations=integrations,- memberships=memberships,- invitations=RegisterServiceOAuthInvitationGateway(session_factory=database_client),- account_claims=RedisOAuthAccountClaimLock(client=redis),- registration=AccountServiceOAuthAccountRegistrationGateway(session_factory=database_client),- workspaces=AccountServiceOAuthWorkspaceGateway(session_factory=database_client),- sessions=AccountServiceOAuthSessionGateway(session_factory=database_client),- registration_policy=policy,- workspace_policy=policy,- supported_languages=languages,- now=naive_utc_now,- )--def build_application_services(*,database_client: sessionmaker[Session],@@ -541,6 +403,7 @@ def build_application_services(database=database_catalog,builtin=builtin_catalog,)+ workspace_repository = WorkspaceRepository(session_factory=database_client)recommended_app_queries = RecommendedAppQueryService(catalog=recommended_app_catalog,trial_apps=trial_apps,@@ -549,11 +412,9 @@ def build_application_services(recommended_app_packages = RecommendedAppPackageService(sources=database_catalog, exporter=RosterAgentPackageExporter())- workspace_query_repository = WorkspaceQueryRepository(session_factory=database_client)- workspace_member_repository = WorkspaceMemberQueryRepository(session_factory=database_client)dataset_dependencies = build_dataset_dependencies(database_client=database_client,- workspace_roles=workspace_member_repository,+ workspace_roles=workspace_repository,)datasource_credentials = build_data_source_credentials(database_client=database_client)data_sources = build_data_source_services(@@ -588,173 +449,51 @@ def build_application_services(remote_file_service = RemoteFileService(files=file_service)passwords = DefaultAccountPasswordHasher()web_authentication_tokens = TokenManagerWebAuthenticationGateway(- reset_password_rate_limiter=AccountService.reset_password_rate_limiter,+ reset_password_rate_limiter=RateLimiter(+ prefix=FORGOT_PASSWORD_SEND_RATE_LIMIT_PREFIX,+ max_attempts=FORGOT_PASSWORD_SEND_RATE_LIMIT_MAX_ATTEMPTS,+ time_window=FORGOT_PASSWORD_SEND_RATE_LIMIT_WINDOW_SECONDS,+ redis_client=redis,+ ),access_token_expire_minutes=dify_config.ACCESS_TOKEN_EXPIRE_MINUTES,)invitation_tokens = RedisInvitationTokenStore(redis=redis)activation_accounts = SQLAlchemyAccountActivationRepository(session_factory=database_client)- account_provisioning = SQLAlchemyConsoleAuthProvisioningGateway(session_factory=database_client)workflow_run_repository = DifyAPISQLAlchemyWorkflowRunRepository(session_maker=database_client)workflow_node_execution_repository = DifyAPIRepositoryFactory.create_api_workflow_node_execution_repository(session_maker=database_client)+ workspace_members, workspace_provisioning = build_workspace_membership_services(+ database_client=database_client,+ workspaces=workspace_repository,+ accounts=accounts,+ )+ account_services = build_account_services(+ database_client=database_client,+ deployment_edition=deployment_edition,+ redis=redis,+ accounts=accounts,+ integrations=integrations,+ workspace_repository=workspace_repository,+ workspace_provisioning=workspace_provisioning,+ passwords=passwords,+ invitation_tokens=invitation_tokens,+ activation_accounts=activation_accounts,+ )+ workspace_services = build_workspace_services(+ workspaces=workspace_repository,+ accounts=accounts,+ files=file_service,+ redis=redis,+ members=workspace_members,+ provisioning=workspace_provisioning,+ registration=account_services.lifecycle,+ invitation_tokens=invitation_tokens,+ )return ApplicationServices(- credential_queries=CredentialQueryRepository(session_factory=database_client),- accounts=AccountServices(- access=AccountAccessService(- accounts=accounts,- workspaces=workspace_query_repository,- sessions=SQLAlchemyOAuthAccessTokenRepository(session_factory=database_client),- invalidate_token_cache=partial(invalidate_oauth_token_cache, redis),- now=utc_now,- ),- 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),- ),- change_email=AccountChangeEmailService(- accounts=accounts,- tokens=TokenManagerChangeEmailTokenGateway(),- codes=SecureChangeEmailCodeGenerator(),- notifications=CeleryChangeEmailNotificationGateway(),- send_limits=RateLimiterChangeEmailSendLimiter(redis=redis),- security=RedisChangeEmailSecurityGateway(- redis=redis,- email_send_ip_limit_per_minute=dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE,- verification_failure_limit=5,- verification_lockout_duration=dify_config.CHANGE_EMAIL_LOCKOUT_DURATION,- ),- email_policy=BillingAccountEmailPolicyGateway(- billing_enabled=deployment_edition == DeploymentEdition.CLOUD,- ),- ),- email_registration=AccountEmailRegistrationService(- accounts=accounts,- tokens=TokenManagerEmailRegistrationTokenGateway(),- codes=SecureEmailRegistrationCodeGenerator(),- notifications=CeleryEmailRegistrationNotificationGateway(),- send_limits=RateLimiterEmailRegistrationSendLimiter(- rate_limiter=RateLimiter(- prefix="email_register_rate_limit",- max_attempts=1,- time_window=60,- redis_client=redis,- )- ),- security=RedisEmailRegistrationSecurityGateway(- redis=redis,- verification_failure_limit=5,- verification_lockout_duration=dify_config.EMAIL_REGISTER_LOCKOUT_DURATION,- ),- account_policy=BillingAccountRegistrationPolicyGateway(- enabled=deployment_edition == DeploymentEdition.CLOUD,- ),- registration=AccountServiceRegistrationGateway(session_factory=database_client),- ),- deletion=AccountDeletionService(- accounts=accounts,- memberships=workspace_query_repository,- verification=TokenManagerAccountDeletionVerificationGateway(),- notifications=CeleryAccountDeletionVerificationNotifier(redis=redis),- synchronization=EnterpriseAccountDeletionSyncGateway(),- scheduler=CeleryAccountDeletionScheduler(),- ),- deletion_feedback=AccountDeletionFeedbackService(- feedback=BillingAccountDeletionFeedbackGateway(),- ),- education=AccountEducationService(- accounts=accounts,- education=BillingAccountEducationGateway(),- verification_rate_limiter=RateLimiter(- prefix="edu_verification_rate_limit",- max_attempts=10,- time_window=60,- redis_client=redis,- ),- activation_rate_limiter=RateLimiter(- prefix="edu_activation_rate_limit",- max_attempts=10,- time_window=60,- redis_client=redis,- ),- ),- forgot_password=AccountForgotPasswordService(- accounts=accounts,- passwords=passwords,- tokens=RedisForgotPasswordTokenGateway(- redis=redis,- expiry_seconds=dify_config.RESET_PASSWORD_TOKEN_EXPIRY_MINUTES * 60,- ),- codes=SecureForgotPasswordCodeGenerator(),- notifications=CeleryForgotPasswordNotificationGateway(),- send_limits=RateLimiterForgotPasswordSendLimiter(redis=redis),- security=RedisForgotPasswordSecurityGateway(- redis=redis,- email_send_ip_limit_per_minute=dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE,- verification_lockout_duration=dify_config.FORGOT_PASSWORD_LOCKOUT_DURATION,- ),- registration=SystemFeatureServiceForgotPasswordRegistrationPolicy(),- ),- initialization=AccountInitializationService(- accounts=accounts,- invitation_required=deployment_edition == DeploymentEdition.CLOUD,- now=naive_utc_now,- ),- integrations=AccountIntegrationService(integrations=integrations),- oauth=_build_account_oauth_service(- database_client=database_client,- deployment_edition=deployment_edition,- redis=redis,- accounts=accounts,- integrations=integrations,- memberships=workspace_query_repository,- ),- password=AccountPasswordService(- accounts=accounts,- passwords=passwords,- ),- profile=AccountProfileService(accounts=accounts),- ),- account_activation=AccountActivationService(- tokens=invitation_tokens,- accounts=activation_accounts,- workspace_policy=DeploymentWorkspaceInvitePolicy(),- eligibility=BillingAccountActivationEligibility(- enabled=deployment_edition == DeploymentEdition.CLOUD,- ),- membership_cache=BillingWorkspaceMembershipCache(- enabled=deployment_edition == DeploymentEdition.CLOUD,- ),- member_access_sync=RBACWorkspaceMemberAccessSync(- enabled=dify_config.RBAC_ENABLED,- ),- ),+ accounts=account_services,apps=apps,+ credential_queries=CredentialQueryRepository(session_factory=database_client),agent_apps=build_agent_app_services(database_client=database_client),advanced_prompt_templates=AdvancedPromptTemplateService(),app_definitions=app_definitions,@@ -804,8 +543,13 @@ def build_application_services(accounts=accounts,passwords=passwords,tokens=web_authentication_tokens,- security=AccountServiceWebAuthenticationSecurityGateway(- account_service=AccountService,+ security=AccountWebAuthenticationSecurityGateway(+ password_security=RedisForgotPasswordSecurityGateway(+ redis=redis,+ email_send_ip_limit_per_minute=dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE,+ verification_lockout_duration=dify_config.FORGOT_PASSWORD_LOCKOUT_DURATION,+ ),+ login_security=RedisConsoleAuthSecurityGateway(redis=redis),),app_access=webapp_access,app_sessions=PassportWebAppSessionGateway(@@ -818,7 +562,7 @@ def build_application_services(installed_apps=build_installed_app_services(database_client=database_client,webapp_access=webapp_access,- get_workspace_role=workspace_query_repository.get_account_role,+ get_workspace_role=workspace_repository.get_account_role,webapp_auth_enabled=webapp_auth_enabled,),web_app_runtime=WebAppRuntimeQueryService(@@ -835,7 +579,12 @@ def build_application_services(schema_definitions=SchemaDefinitionService(source_factory=SchemaManager),setup=SetupService(state=installation_state,- accounts=RegisterServiceAccountProvisioner(session_factory=database_client),+ accounts=AccountSetupProvisioner(+ accounts=account_services.lifecycle,+ workspaces=workspace_services.provisioning,+ installation=installation_state,+ telemetry=InstallationTelemetryGateway(session_factory=database_client),+ ),lock=RedisSetupLock(client=redis),setup_required=deployment_edition != DeploymentEdition.CLOUD,),@@ -872,7 +621,7 @@ def build_application_services(database_client=database_client,redis=redis,accounts=accounts,- workspaces=workspace_query_repository,+ workspaces=workspace_repository,),init_validation=InitValidationService(state=installation_state,@@ -910,14 +659,7 @@ def build_application_services(workflow_runs=workflow_run_repository,node_executions=workflow_node_execution_repository,),- workspace_queries=WorkspaceQueryService(- workspaces=workspace_query_repository,- plans=DeploymentWorkspacePlanGateway(),- ),- workspace_member_queries=WorkspaceMemberQueryService(- members=workspace_member_repository,- roles=DeploymentWorkspaceMemberRoleResolver(),- ),+ workspaces=workspace_services,workflow_app_logs=WorkflowAppLogQueryService(logs=WorkflowAppLogQueryRepository(session_factory=database_client),),@@ -945,12 +687,16 @@ def build_application_services(def init_app(app: Flask) -> None:- app.extensions[_EXTENSION_KEY] = build_application_services(+ from extensions.ext_login import bind_account_loader++ services = build_application_services(database_client=get_session_maker(),deployment_edition=dify_config.DEPLOYMENT_EDITION,initialization_password=dify_config.INIT_PASSWORD,redis=redis_client,)+ app.extensions[_EXTENSION_KEY] = services+ bind_account_loader(app, services.accounts.identity.load_user)def application_services() -> ApplicationServices:diff --git a/api/extensions/ext_login.py b/api/extensions/ext_login.pyindex 4b91a2320a3..d0d74c2990e 100644--- a/api/extensions/ext_login.py+++ b/api/extensions/ext_login.py@@ -1,9 +1,10 @@import jsonimport logging+from collections.abc import Callablefrom typing import assert_never, cast, overrideimport flask_login-from flask import Request, Response, request+from flask import Flask, Request, Response, current_app, requestfrom flask_login import user_loaded_from_request, user_logged_infrom sqlalchemy import selectfrom sqlalchemy.orm import Session@@ -24,11 +25,19 @@ from libs.token import (from models import Account, Tenant, TenantAccountJoinfrom models.enums import EndUserTypefrom models.model import AppMCPServer, EndUser-from services.account_service import AccountServicelogger = logging.getLogger(__name__)type LoginUser = Account | EndUser+type AccountLoader = Callable[[str], Account | None]+++def bind_account_loader(app: Flask, loader: AccountLoader) -> None:+ app.extensions["account_identity_loader"] = loader+++def load_account(account_id: str) -> Account | None:+ return cast(AccountLoader, current_app.extensions["account_identity_loader"])(account_id)class DifyLoginManager(flask_login.LoginManager):@@ -99,7 +108,7 @@ def _load_user_from_request(request_from_flask_login: Request, session: Session)if not user_id:raise Unauthorized("Invalid Authorization token.")- logged_in_account = AccountService.load_logged_in_account(account_id=user_id, session=session)+ logged_in_account = load_account(user_id)return logged_in_accountelif request.blueprint == "openapi":# Account-branch device-flow approval routes (approve / deny /@@ -118,7 +127,7 @@ def _load_user_from_request(request_from_flask_login: Request, session: Session)source = decoded.get("token_source")if source or not user_id:return None- return AccountService.load_logged_in_account(account_id=user_id, session=session)+ return load_account(user_id)elif request.blueprint == "web":app_code = request.headers.get(HEADER_NAME_APP_CODE)webapp_token = extract_webapp_passport(app_code, request) if app_code else None@@ -166,7 +175,7 @@ def _load_user_from_request(request_from_flask_login: Request, session: Session)def on_user_logged_in(_sender: object, user: LoginUser) -> None:"""Snapshot authenticated identity into the side-effect-free logging context.- Note: AccountService.load_logged_in_account will populate user.current_tenant_id+ Note: AccountIdentityGateway.load_user will populate user.current_tenant_idthrough the load_user method, which calls account.set_tenant_id_with_session()."""set_identity_context()diff --git a/api/models/account.py b/api/models/account.pyindex c30fd805c06..3ad54f2de32 100644--- a/api/models/account.py+++ b/api/models/account.py@@ -2,7 +2,7 @@ import enumimport jsonfrom dataclasses import fieldfrom datetime import datetime-from typing import Optional, TypedDict+from typing import TypedDictfrom uuid import uuid4import sqlalchemy as sa@@ -12,71 +12,12 @@ from sqlalchemy.orm import Mapped, Session, mapped_columnfrom typing_extensions import deprecatedfrom configs import dify_config+from enums.account import TenantAccountRolefrom .base import TypeBasefrom .types import EnumText, LongText, StringUUID-class TenantAccountRole(enum.StrEnum):- OWNER = "owner"- ADMIN = "admin"- EDITOR = "editor"- NORMAL = "normal"- DATASET_OPERATOR = "dataset_operator"-- @staticmethod- def is_valid_role(role: str) -> bool:- if not role:- return False- return role in {- TenantAccountRole.OWNER,- TenantAccountRole.ADMIN,- TenantAccountRole.EDITOR,- TenantAccountRole.NORMAL,- TenantAccountRole.DATASET_OPERATOR,- }-- @staticmethod- def is_privileged_role(role: Optional["TenantAccountRole"]) -> bool:- if not role:- return False- return role in {TenantAccountRole.OWNER, TenantAccountRole.ADMIN}-- @staticmethod- def is_admin_role(role: Optional["TenantAccountRole"]) -> bool:- if not role:- return False- return role == TenantAccountRole.ADMIN-- @staticmethod- def is_non_owner_role(role: Optional["TenantAccountRole"]) -> bool:- if not role:- return False- return role in {- TenantAccountRole.ADMIN,- TenantAccountRole.EDITOR,- TenantAccountRole.NORMAL,- TenantAccountRole.DATASET_OPERATOR,- }-- @staticmethod- def is_editing_role(role: Optional["TenantAccountRole"]) -> bool:- if not role:- return False- return role in {TenantAccountRole.OWNER, TenantAccountRole.ADMIN, TenantAccountRole.EDITOR}-- @staticmethod- def is_dataset_edit_role(role: Optional["TenantAccountRole"]) -> bool:- if not role:- return False- return role in {- TenantAccountRole.OWNER,- TenantAccountRole.ADMIN,- TenantAccountRole.EDITOR,- TenantAccountRole.DATASET_OPERATOR,- }--class AccountStatus(enum.StrEnum):PENDING = "pending"UNINITIALIZED = "uninitialized"diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.mdindex 039606e5652..2f4d95bc57d 100644--- a/api/openapi/markdown/console-openapi.md+++ b/api/openapi/markdown/console-openapi.md@@ -10848,10 +10848,6 @@ Update a plugin endpoint| 200 | Available models retrieved successfully | **application/json**: [AvailableModelListResponse](#availablemodellistresponse)<br> |### [GET] /workspaces/current/permission-**Get workspace permission settings**--Returns permission flags that control workspace features like member invitations and owner transfer.-#### Responses| Code | Description | Schema |diff --git a/api/repositories/account/__init__.py b/api/repositories/account/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/api/repositories/account_repository.py b/api/repositories/account/repository.pysimilarity index 63%rename from api/repositories/account_repository.pyrename to api/repositories/account/repository.pyindex 9d758e3cc4b..ed497d6a403 100644--- a/api/repositories/account_repository.py+++ b/api/repositories/account/repository.py@@ -3,12 +3,23 @@from datetime import datetimefrom typing import override-from sqlalchemy import case, delete, func, select+from sqlalchemy import case, delete, func, select, updatefrom sqlalchemy.orm import Session, sessionmaker-from models.account import Account, AccountIntegrate, AccountStatus, InvitationCode, InvitationCodeStatus+from models.account import (+ Account,+ AccountIntegrate,+ AccountStatus,+ InvitationCode,+ InvitationCodeStatus,+ Tenant,+ TenantAccountJoin,+ TenantStatus,+)+from services.account.contracts import AccountCreation+from services.account.login_service import ConsoleAuthAccountRepositoryfrom services.account_email import normalize_email-from services.account_login_service import ConsoleAuthAccountRepository+from services.account_errors import AccountNormalizedEmailAlreadyInUseErrorfrom services.account_ports import AccountRepositoryfrom services.entities.account_entities import (AccountAuthenticationSnapshot,@@ -35,18 +46,136 @@ class SQLAlchemyAccountRepository(AccountRepository, ConsoleAuthAccountRepositor@overridedef get(self, account_id: str) -> AccountSnapshot | None:+ account = self.get_model(account_id)+ return self._to_snapshot(account) if account is not None else None++ def get_model(self, account_id: str) -> Account | None:+ """Load a detached identity for framework adapters that require Account."""+ with self._session_factory() as session:+ return session.get(Account, account_id)++ def find_identity(self, email: str, *, case_fallback: bool = False) -> Account | None:+ """Prefer an exact email match, then the oldest normalized match when requested.++ SSO identities can retain mixed-case emails while callers supply lowercase+ addresses. Normalized emails are indexed but may have historical duplicates.+ """with self._session_factory() as session:+ account = session.execute(select(Account).where(Account.email == email)).scalar_one_or_none()+ if account is None and case_fallback:+ account = session.execute(+ select(Account)+ .where(Account.normalized_email == normalize_email(email))+ .order_by(Account.created_at)+ .limit(1)+ ).scalar_one_or_none()+ return account++ def load_identity(self, account_id: str, *, now: datetime) -> Account | None:+ """Resolve an active workspace and materialize the Flask identity before closing its Session."""+ with self._session_factory(expire_on_commit=False) as session:account = session.get(Account, account_id)- return self._to_snapshot(account) if account is not None else None+ if account is None or account.status == AccountStatus.BANNED:+ return account+ 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 membership is None:+ session.execute(+ update(TenantAccountJoin)+ .where(TenantAccountJoin.account_id == account_id, TenantAccountJoin.current.is_(True))+ .values(current=False)+ )+ 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 membership is None:+ session.commit()+ return None+ membership.current = True+ membership.last_opened_at = now+ session.commit()+ account.set_tenant_id_with_session(membership.tenant_id, session=session)+ return account++ def touch_activity(self, account_id: str, *, now: datetime, before: datetime, touch_updated_at: bool) -> None:+ with self._session_factory.begin() as session:+ values: dict[str, object] = {"last_active_at": now}+ if touch_updated_at:+ values["updated_at"] = func.current_timestamp()+ session.execute(+ update(Account).where(Account.id == account_id, Account.last_active_at < before).values(**values)+ )@overridedef find_by_email(self, email: str) -> AccountSnapshot | None:+ account = self.find_identity(email, case_fallback=True)+ return self._to_snapshot(account) if account is not None else None++ def find_first_by_email(self, email: str) -> AccountSnapshot | None:+ """Preserve internal provisioning's exact, first-match email lookup.++ Accounts may still have duplicate email addresses during normalization;+ unlike authentication, this endpoint historically selects one match.+ """with self._session_factory() as session:- account = session.execute(select(Account).where(Account.email == email)).scalar_one_or_none()- if account is None and email != email.lower():- account = session.execute(select(Account).where(Account.email == email.lower())).scalar_one_or_none()+ account = session.scalar(select(Account).where(Account.email == email).limit(1))return self._to_snapshot(account) if account is not None else None+ def normalized_email_exists(self, email: str) -> bool:+ with self._session_factory() as session:+ return (+ session.scalar(select(Account.id).where(Account.normalized_email == normalize_email(email)).limit(1))+ is not None+ )++ def create(self, creation: AccountCreation) -> AccountSnapshot:+ with self._session_factory.begin() as session:+ return self._to_snapshot(self.add(creation, session=session))++ @staticmethod+ def add(creation: AccountCreation, *, session: Session) -> Account:+ """Share account insertion with aggregate repositories without owning their commit."""+ if (+ creation.check_normalized_email+ and session.scalar(+ select(Account.id).where(Account.normalized_email == normalize_email(creation.email)).limit(1)+ )+ is not None+ ):+ raise AccountNormalizedEmailAlreadyInUseError("An account with an equivalent email already exists.")+ account = Account(+ name=creation.name,+ email=creation.email,+ normalized_email=normalize_email(creation.email),+ password=creation.password.password_hash if creation.password else None,+ password_salt=creation.password.password_salt if creation.password else None,+ interface_language=creation.interface_language,+ interface_theme=creation.interface_theme,+ timezone=creation.timezone,+ last_login_ip=creation.ip_address,+ status=AccountStatus(creation.status),+ initialized_at=creation.initialized_at,+ )+ account.id = creation.id+ session.add(account)+ session.flush()+ return account+@overridedef activate_pending(self, account_id: str, *, initialized_at: datetime) -> None:with self._session_factory.begin() as session:@@ -208,6 +337,16 @@ class SQLAlchemyAccountRepository(AccountRepository, ConsoleAuthAccountRepositorwith self._session_factory() as session:return session.scalar(select(Account.id).where(Account.email == email).limit(1)) is not None+ def set_email(self, account_id: str, email: str) -> None:+ with self._session_factory.begin() as session:+ account = session.get(Account, account_id)+ if account is None:+ from services.account_errors import AccountNotFoundError++ raise AccountNotFoundError()+ account.email = email+ account.normalized_email = normalize_email(email)+@overridedef has_active_email(self, email: str) -> bool:normalized = email.strip().lower()diff --git a/api/repositories/account_oauth_repository.py b/api/repositories/account_oauth_repository.pydeleted file mode 100644index 3f43cfeb54e..00000000000--- a/api/repositories/account_oauth_repository.py+++ /dev/null@@ -1,128 +0,0 @@-"""Persistence-backed gateways for Console account OAuth sign-in."""--from typing import override--from sqlalchemy.orm import Session, sessionmaker--from libs.datetime_utils import naive_utc_now-from models.account import Account, AccountStatus-from services.account_errors import (- AccountEmailDomainSuspendedError,- OAuthAccountNotFoundError,- OAuthRegistrationError,- OAuthSeatsLimitExceededError,- OAuthWorkspaceCreationNotAllowedError,-)-from services.account_oauth_service import (- OAuthAccountRegistrationGateway,- OAuthInvitationGateway,- OAuthSessionGateway,- OAuthWorkspaceGateway,-)-from services.account_service import AccountService, RegisterService, TenantService-from services.enterprise.enterprise_service import try_join_default_workspace-from services.entities.account_entities import AccountSessionTokens-from services.entities.account_oauth_entities import (- OAuthAccountRegistration,- OAuthInvitation,-)-from services.errors.account import AccountRegisterError, EmailDomainSuspendedError, SeatsLimitExceededError-from services.errors.workspace import WorkSpaceNotAllowedCreateError, WorkspacesLimitExceededError---class RegisterServiceOAuthInvitationGateway(OAuthInvitationGateway):- def __init__(self, *, session_factory: sessionmaker[Session]) -> None:- self._session_factory = session_factory-- @override- def resolve(self, invite_token: str) -> OAuthInvitation | None:- with self._session_factory() as session:- invitation = RegisterService.get_invitation_if_token_valid(- None,- None,- invite_token,- session=session,- )- if invitation is None:- return None- account = invitation["account"]- return OAuthInvitation(- account_id=account.id,- account_email=account.email,- account_status=account.status.value,- )---class AccountServiceOAuthAccountRegistrationGateway(OAuthAccountRegistrationGateway):- def __init__(self, *, session_factory: sessionmaker[Session]) -> None:- self._session_factory = session_factory-- @override- def register(self, registration: OAuthAccountRegistration) -> str:- with self._session_factory() as session:- try:- account = AccountService.create_account(- email=registration.email,- name=registration.name,- interface_language=registration.language,- password=None,- timezone=registration.timezone,- ip_address=registration.ip_address,- check_normalized_email=True,- session=session,- )- account.status = AccountStatus.ACTIVE- account.initialized_at = naive_utc_now()- session.commit()- except EmailDomainSuspendedError as exc:- raise AccountEmailDomainSuspendedError from exc- except SeatsLimitExceededError as exc:- raise OAuthSeatsLimitExceededError from exc- except AccountRegisterError as exc:- raise OAuthRegistrationError(exc.description) from exc- except Exception as exc:- session.rollback()- raise OAuthRegistrationError(f"Registration failed: {exc}") from exc- return account.id---class AccountServiceOAuthWorkspaceGateway(OAuthWorkspaceGateway):- """Adapt account workspace operations to the OAuth application port."""-- def __init__(self, *, session_factory: sessionmaker[Session]) -> None:- self._session_factory = session_factory-- @override- def create_owner_workspace(self, account_id: str) -> None:- with self._session_factory() as session:- account = session.get(Account, account_id)- if account is None:- raise OAuthAccountNotFoundError- try:- TenantService.create_owner_tenant(account, session=session)- except (WorkSpaceNotAllowedCreateError, WorkspacesLimitExceededError) as exc:- raise OAuthWorkspaceCreationNotAllowedError from exc-- @override- def try_join_default_workspace(self, account_id: str) -> None:- try_join_default_workspace(account_id)---class AccountServiceOAuthSessionGateway(OAuthSessionGateway):- """Adapt Console session issuance to the OAuth application port."""-- def __init__(self, *, session_factory: sessionmaker[Session]) -> None:- self._session_factory = session_factory-- @override- def login(self, account_id: str, *, ip_address: str) -> AccountSessionTokens:- with self._session_factory() as session:- account = session.get(Account, account_id)- if account is None:- raise OAuthAccountNotFoundError- token_pair = AccountService.login(account=account, session=session, ip_address=ip_address)- return AccountSessionTokens(- access_token=token_pair.access_token,- refresh_token=token_pair.refresh_token,- csrf_token=token_pair.csrf_token,- )diff --git a/api/repositories/app/console_repository.py b/api/repositories/app/console_repository.pyindex a6d52435482..07f4fcfc01f 100644--- a/api/repositories/app/console_repository.py+++ b/api/repositories/app/console_repository.py@@ -70,7 +70,7 @@ from services.entities.app_entities import (StarredAppListParams,UpdateAppParams,)-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.openapi.visibility import apply_openapi_gate, is_openapi_visiblelogger = logging.getLogger(__name__)diff --git a/api/repositories/installation_state_repository.py b/api/repositories/installation_state_repository.pyindex f34b3c54fa9..5a833c147d3 100644--- a/api/repositories/installation_state_repository.py+++ b/api/repositories/installation_state_repository.py@@ -1,11 +1,13 @@"""Persistence adapter for installation setup and tenant-existence state."""from datetime import datetime+from uuid import uuid4-from sqlalchemy import exists, select+from sqlalchemy import delete, exists, selectfrom sqlalchemy.orm import Session, sessionmaker-from models.account import Tenant+from configs import dify_config+from models.account import Account, Tenant, TenantAccountJoinfrom models.model import DifySetup@@ -25,3 +27,12 @@ class InstallationStateRepository:def has_tenants(self) -> bool:with self._session_factory() as session:return session.scalar(select(exists().select_from(Tenant))) is True++ def mark_setup(self) -> None:+ with self._session_factory.begin() as session:+ session.add(DifySetup(version=dify_config.project.version, instance_id=str(uuid4())))++ def reset_setup(self) -> None:+ with self._session_factory.begin() as session:+ for model in (DifySetup, TenantAccountJoin, Account, Tenant):+ session.execute(delete(model))diff --git a/api/repositories/workspace/__init__.py b/api/repositories/workspace/__init__.pynew file mode 100644index 00000000000..d2cb6cc36e6--- /dev/null+++ b/api/repositories/workspace/__init__.py@@ -0,0 +1 @@+"""Workspace domain modules."""diff --git a/api/repositories/workspace/workspace_repository.py b/api/repositories/workspace/workspace_repository.pynew file mode 100644index 00000000000..4c5639e8dec--- /dev/null+++ b/api/repositories/workspace/workspace_repository.py@@ -0,0 +1,561 @@+"""Workspace persistence shared by account queries and workspace use cases."""++from collections.abc import Callable, Sequence+from dataclasses import replace+from typing import override++from sqlalchemy import func, select, update+from sqlalchemy.orm import Session, sessionmaker++from libs.datetime_utils import naive_utc_now+from libs.pagination import paginate_query+from models import TenantCreditPool+from models.account import (+ Account,+ AccountStatus,+ Tenant,+ TenantAccountJoin,+ TenantAccountRole,+ TenantPluginAutoUpgradeCategory,+ TenantPluginAutoUpgradeMode,+ TenantPluginAutoUpgradeStrategy,+ TenantPluginAutoUpgradeStrategySetting,+ TenantStatus,+)+from models.dataset import Dataset+from models.enums import ProviderQuotaType+from models.model import App+from repositories.account.repository import SQLAlchemyAccountRepository+from services.account.contracts import AccountCreation+from services.account.login_service import ConsoleAuthWorkspaceQuery+from services.account_ports import AccountWorkspaceMembershipQuery, AccountWorkspaceSnapshotQuery+from services.entities.account_access_entities import AccountWorkspaceSnapshot+from services.errors.workspace import (+ MemberNotInTenantError,+ WorkspaceNotFoundError,+ WorkspaceNotLinkedError,+ WorkspaceOwnerNotFoundError,+)+from services.oauth_device_application_service import DeviceWorkspaceQuery+from services.oauth_device_contracts import DeviceWorkspace+from services.workspace.contracts import (+ CreatedWorkspace,+ WorkspaceCreation,+ WorkspaceCustomConfig,+ WorkspaceMemberRecord,+ WorkspaceMemberRemoval,+ WorkspaceMemberWrite,+ WorkspacePage,+ WorkspaceRecord,+ WorkspaceSnapshot,+)+from services.workspace.member_service import WorkspaceMemberQuery+from services.workspace.service import WorkspaceQuery, WorkspaceStore+++class WorkspaceRepository(+ WorkspaceStore,+ WorkspaceQuery,+ AccountWorkspaceMembershipQuery,+ AccountWorkspaceSnapshotQuery,+ ConsoleAuthWorkspaceQuery,+ DeviceWorkspaceQuery,+ WorkspaceMemberQuery,+):+ def __init__(self, session_factory: sessionmaker[Session]) -> None:+ self._session_factory = session_factory++ def get_account_role(self, *, account_id: str, tenant_id: str) -> str | None:+ """Read the current membership role without loading or mutating an Account."""+ stmt = (+ select(TenantAccountJoin.role)+ .where(TenantAccountJoin.account_id == account_id, TenantAccountJoin.tenant_id == tenant_id)+ .limit(1)+ )+ with self._session_factory() as session:+ role = session.scalar(stmt)+ return role.value if role is not None else None++ def provision(+ self,+ prepare: Callable[[], WorkspaceCreation],+ *,+ owner_id: str | None,+ account: AccountCreation | None = None,+ only_if_no_active_workspace: bool = False,+ ) -> CreatedWorkspace | None:+ """Commit the account, workspace, membership and defaults as one aggregate.++ Initial-workspace creation holds the owner's row lock from the existence+ check through preparation and commit. Preparation deliberately runs inside+ this transaction: private-key writes and RBAC bindings cannot be rolled+ back locally, so a competing sign-in must skip before creating either.+ The application supplies these external actions; this repository only+ controls when they can run. Notifications run after this method commits.+ """+ with self._session_factory.begin() as session:+ if account is not None:+ owner_id = SQLAlchemyAccountRepository.add(account, session=session).id+ elif owner_id is not None:+ owner = session.get(Account, owner_id, with_for_update=only_if_no_active_workspace)+ if owner is None:+ raise WorkspaceOwnerNotFoundError()+ if (+ only_if_no_active_workspace+ and session.scalar(+ select(Tenant.id)+ .join(TenantAccountJoin, TenantAccountJoin.tenant_id == Tenant.id)+ .where(TenantAccountJoin.account_id == owner_id, Tenant.status == TenantStatus.NORMAL)+ .limit(1)+ )+ is not None+ ):+ return None+ creation = prepare()+ tenant = Tenant(name=creation.name, encrypt_public_key=creation.encrypt_public_key)+ tenant.id = creation.id+ session.add(tenant)+ if owner_id is not None:+ session.add(TenantAccountJoin(tenant_id=tenant.id, account_id=owner_id, role=TenantAccountRole.OWNER))+ for category, setting in creation.plugin_upgrade_settings.items():+ session.add(+ TenantPluginAutoUpgradeStrategy(+ tenant_id=tenant.id,+ category=TenantPluginAutoUpgradeCategory(category),+ strategy_setting=TenantPluginAutoUpgradeStrategySetting(setting),+ upgrade_time_of_day=creation.plugin_upgrade_time,+ upgrade_mode=TenantPluginAutoUpgradeMode.EXCLUDE,+ exclude_plugins=[],+ include_plugins=[],+ )+ )+ session.add(+ TenantCreditPool(+ tenant_id=tenant.id,+ quota_limit=creation.trial_credits,+ quota_used=0,+ pool_type=ProviderQuotaType.TRIAL,+ )+ )+ session.flush()+ return CreatedWorkspace(+ tenant.id,+ tenant.name,+ tenant.plan,+ tenant.status.value,+ tenant.created_at,+ tenant.updated_at,+ tenant.encrypt_public_key,+ dict(tenant.custom_config_dict),+ )++ @override+ def list_for_account(self, account_id: str) -> tuple[WorkspaceRecord, ...]:+ stmt = (+ select(+ Tenant.id,+ Tenant.name,+ Tenant.status,+ Tenant.created_at,+ TenantAccountJoin.last_opened_at,+ )+ .join(TenantAccountJoin, TenantAccountJoin.tenant_id == Tenant.id)+ .where(+ TenantAccountJoin.account_id == account_id,+ Tenant.status == TenantStatus.NORMAL,+ )+ .order_by(Tenant.created_at.asc())+ )++ with self._session_factory() as session:+ rows = session.execute(stmt).all()+ return tuple(+ WorkspaceRecord(+ id=workspace_id,+ name=name,+ status=status.value,+ created_at=created_at,+ last_opened_at=last_opened_at,+ )+ for workspace_id, name, status, created_at, last_opened_at in rows+ )++ @override+ def list_ids_for_account(self, account_id: str) -> tuple[str, ...]:+ 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 list_account_access_workspaces(self, account_id: str) -> tuple[AccountWorkspaceSnapshot, ...]:+ """List every membership for the OpenAPI account identity response.++ Unlike the Console workspace picker, the identity response preserves+ its existing behavior of including archived memberships.+ """+ stmt = (+ select(+ Tenant.id,+ Tenant.name,+ TenantAccountJoin.role,+ TenantAccountJoin.current,+ )+ .join(TenantAccountJoin, TenantAccountJoin.tenant_id == Tenant.id)+ .where(TenantAccountJoin.account_id == account_id)+ .order_by(Tenant.created_at.asc(), Tenant.id.asc())+ )+ with self._session_factory() as session:+ return tuple(+ AccountWorkspaceSnapshot(+ id=workspace_id,+ name=name,+ role=role.value,+ current=current,+ )+ for workspace_id, name, role, current in session.execute(stmt).all()+ )++ @override+ def list_for_device_flow(self, account_id: str) -> tuple[DeviceWorkspace, ...]:+ return tuple(+ DeviceWorkspace(+ id=workspace.id,+ name=workspace.name,+ role=workspace.role,+ current=workspace.current,+ )+ for workspace in self.list_account_access_workspaces(account_id)+ )++ @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 None++ @override+ def has_active_membership(self, account_id: str) -> bool:+ return self.has_active_for_account(account_id)++ @override+ def list_all(self, *, page: int, limit: int) -> WorkspacePage:+ with self._session_factory() as session:+ result = paginate_query(+ select(Tenant).order_by(Tenant.created_at.desc()), session=session, page=page, per_page=limit+ )+ return WorkspacePage(+ data=tuple(self._snapshot(tenant) for tenant in result.items),+ total=result.total,+ page=result.page,+ limit=result.per_page,+ has_more=result.has_next,+ )++ @staticmethod+ def _snapshot(+ tenant: Tenant, role: TenantAccountRole | None = None, *, has_privileged_member: bool = False+ ) -> WorkspaceSnapshot:+ config = tenant.custom_config_dict+ return WorkspaceSnapshot(+ id=tenant.id,+ name=tenant.name,+ status=tenant.status.value,+ created_at=tenant.created_at,+ role=role.value if role is not None else None,+ custom_config=WorkspaceCustomConfig(+ remove_webapp_brand=config.get("remove_webapp_brand", False),+ replace_webapp_logo=config.get("replace_webapp_logo"),+ ),+ has_privileged_member=has_privileged_member,+ )++ @classmethod+ def _account_snapshot(cls, session: Session, tenant: Tenant, account_id: str) -> WorkspaceSnapshot:+ role = session.scalar(+ select(TenantAccountJoin.role).where(+ TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == account_id+ )+ )+ if role is None:+ raise WorkspaceNotFoundError()+ return cls._snapshot(+ tenant,+ role,+ has_privileged_member=session.scalar(+ select(TenantAccountJoin.id)+ .where(+ TenantAccountJoin.tenant_id == tenant.id,+ TenantAccountJoin.role.in_([TenantAccountRole.OWNER, TenantAccountRole.ADMIN]),+ )+ .limit(1)+ )+ is not None,+ )++ @override+ def get_for_account(self, workspace_id: str, account_id: str) -> WorkspaceSnapshot | None:+ with self._session_factory() as session:+ tenant = session.get(Tenant, workspace_id)+ return self._account_snapshot(session, tenant, account_id) if tenant is not None else None++ @override+ def switch(self, *, account_id: str, workspace_id: str) -> WorkspaceSnapshot:+ with self._session_factory(expire_on_commit=False) as session:+ account = session.get(Account, account_id)+ if account is None:+ raise WorkspaceNotLinkedError()+ membership = session.scalar(+ select(TenantAccountJoin)+ .join(Tenant, Tenant.id == TenantAccountJoin.tenant_id)+ .where(+ TenantAccountJoin.account_id == account_id,+ TenantAccountJoin.tenant_id == workspace_id,+ Tenant.status == TenantStatus.NORMAL,+ )+ .limit(1)+ )+ if membership is None:+ raise WorkspaceNotLinkedError()+ session.execute(+ update(TenantAccountJoin)+ .where(TenantAccountJoin.account_id == account_id, TenantAccountJoin.tenant_id != workspace_id)+ .values(current=False)+ )+ membership.current = True+ membership.last_opened_at = naive_utc_now()+ session.commit()+ tenant = session.get(Tenant, workspace_id)+ if tenant is None:+ raise WorkspaceNotFoundError()+ return replace(self._account_snapshot(session, tenant, account_id), current=True)++ def get(self, workspace_id: str) -> WorkspaceSnapshot | None:+ with self._session_factory() as session:+ tenant = session.get(Tenant, workspace_id)+ return self._snapshot(tenant) if tenant else None++ def get_model(self, workspace_id: str) -> Tenant | None:+ """Materialize a workspace identity for admission adapters."""+ with self._session_factory() as session:+ return session.get(Tenant, workspace_id)++ def get_many(self, workspace_ids: Sequence[str]) -> tuple[WorkspaceSnapshot, ...]:+ if not workspace_ids:+ return ()+ with self._session_factory() as session:+ return tuple(+ self._snapshot(tenant) for tenant in session.scalars(select(Tenant).where(Tenant.id.in_(workspace_ids)))+ )++ def list_memberships(self, account_id: str) -> tuple[WorkspaceSnapshot, ...]:+ with self._session_factory() as session:+ rows = session.execute(+ select(Tenant, TenantAccountJoin)+ .join(TenantAccountJoin, Tenant.id == TenantAccountJoin.tenant_id)+ .where(TenantAccountJoin.account_id == account_id)+ .order_by(Tenant.created_at.asc())+ )+ return tuple(replace(self._snapshot(tenant, join.role), current=join.current) for tenant, join in rows)++ def find_membership(self, account_id: str, workspace_id: str) -> WorkspaceSnapshot | None:+ with self._session_factory() as session:+ row = session.execute(+ select(Tenant, TenantAccountJoin)+ .join(TenantAccountJoin, Tenant.id == TenantAccountJoin.tenant_id)+ .where(Tenant.id == workspace_id, TenantAccountJoin.account_id == account_id)+ ).first()+ return replace(self._snapshot(row[0], row[1].role), current=row[1].current) if row else None++ def member_role(self, workspace_id: str, account_id: str | None) -> TenantAccountRole | None:+ if not account_id:+ return None+ with self._session_factory() as session:+ return session.execute(+ select(TenantAccountJoin.role).where(+ TenantAccountJoin.tenant_id == workspace_id, TenantAccountJoin.account_id == account_id+ )+ ).scalar_one_or_none()++ def get_legacy_role(self, *, workspace_id: str, account_id: str) -> str | None:+ """Return one member's role without loading the whole workspace roster."""+ role = self.member_role(workspace_id, account_id)+ return role.value if role is not None else None++ @override+ def list_for_workspace(+ self, workspace_id: str, *, role: TenantAccountRole | None = None+ ) -> tuple[WorkspaceMemberRecord, ...]:+ """Read membership snapshots without retaining a Session during role resolution."""+ stmt = (+ select(+ Account.id,+ Account.name,+ Account.email,+ Account.avatar,+ Account.last_login_at,+ Account.last_active_at,+ Account.created_at,+ Account.status,+ TenantAccountJoin.role,+ )+ .select_from(Account)+ .join(TenantAccountJoin, TenantAccountJoin.account_id == Account.id)+ .where(TenantAccountJoin.tenant_id == workspace_id)+ )+ if role is not None:+ stmt = stmt.where(TenantAccountJoin.role == role)++ with self._session_factory() as session:+ return tuple(+ WorkspaceMemberRecord(+ id=account_id,+ name=name,+ email=email,+ avatar=avatar,+ last_login_at=last_login_at,+ last_active_at=last_active_at,+ created_at=created_at,+ status=status.value,+ legacy_role=member_role.value,+ )+ for (+ account_id,+ name,+ email,+ avatar,+ last_login_at,+ last_active_at,+ created_at,+ status,+ member_role,+ ) in session.execute(stmt).all()+ )++ def owner_id(self, workspace_id: str) -> str | None:+ with self._session_factory() as session:+ return session.scalar(+ select(TenantAccountJoin.account_id)+ .where(TenantAccountJoin.tenant_id == workspace_id, TenantAccountJoin.role == TenantAccountRole.OWNER)+ .limit(1)+ )++ def upsert_member(self, *, workspace_id: str, account_id: str, role: TenantAccountRole) -> WorkspaceMemberWrite:+ with self._session_factory.begin() as session:+ account = session.get(Account, account_id)+ if account is None:+ raise MemberNotInTenantError("Member not in tenant.")+ membership = session.scalar(+ select(TenantAccountJoin)+ .where(TenantAccountJoin.tenant_id == workspace_id, TenantAccountJoin.account_id == account_id)+ .limit(1)+ )+ created = membership is None+ if membership is None:+ session.add(TenantAccountJoin(tenant_id=workspace_id, account_id=account_id, role=role))+ else:+ membership.role = role+ return WorkspaceMemberWrite(workspace_id, account_id, role.value, account.status.value, created)++ def remove_member(self, *, workspace_id: str, account_id: str, owner_id: str) -> WorkspaceMemberRemoval:+ with self._session_factory.begin() as session:+ account = session.get(Account, account_id)+ membership = session.scalar(+ select(TenantAccountJoin)+ .where(TenantAccountJoin.tenant_id == workspace_id, TenantAccountJoin.account_id == account_id)+ .limit(1)+ )+ if account is None or membership is None:+ raise MemberNotInTenantError("Member not in tenant.")+ session.execute(+ update(App)+ .where(App.tenant_id == workspace_id, App.maintainer == account_id)+ .values(maintainer=owner_id)+ )+ session.execute(+ update(Dataset)+ .where(Dataset.tenant_id == workspace_id, Dataset.maintainer == account_id)+ .values(maintainer=owner_id)+ )+ session.delete(membership)+ delete_account = account.status == AccountStatus.PENDING and not session.scalar(+ select(func.count(TenantAccountJoin.id)).where(TenantAccountJoin.account_id == account_id)+ )+ email = account.email+ if delete_account:+ session.delete(account)+ return WorkspaceMemberRemoval(account_id, email, delete_account)++ def update_member_role(self, *, workspace_id: str, account_id: str, role: TenantAccountRole) -> None:+ with self._session_factory.begin() as session:+ membership = session.scalar(+ select(TenantAccountJoin)+ .where(TenantAccountJoin.tenant_id == workspace_id, TenantAccountJoin.account_id == account_id)+ .limit(1)+ )+ if membership is None:+ raise MemberNotInTenantError("Member not in tenant.")+ if role == TenantAccountRole.OWNER:+ owner = session.scalar(+ select(TenantAccountJoin)+ .where(+ TenantAccountJoin.tenant_id == workspace_id, TenantAccountJoin.role == TenantAccountRole.OWNER+ )+ .limit(1)+ )+ if owner:+ owner.role = TenantAccountRole.NORMAL+ membership.role = role++ def list_member_ids(self, workspace_id: str, *, offset: int, limit: int) -> tuple[str, ...]:+ with self._session_factory() as session:+ return tuple(+ session.scalars(+ select(TenantAccountJoin.account_id)+ .where(TenantAccountJoin.tenant_id == workspace_id)+ .order_by(TenantAccountJoin.id)+ .offset(offset)+ .limit(limit)+ )+ )++ def count_members(self, workspace_id: str) -> int:+ with self._session_factory() as session:+ return (+ session.scalar(+ select(func.count(TenantAccountJoin.id)).where(TenantAccountJoin.tenant_id == workspace_id)+ )+ or 0+ )++ @override+ def rename(self, *, workspace_id: str, account_id: str, name: str) -> WorkspaceSnapshot:+ with self._session_factory.begin() as session:+ tenant = session.get(Tenant, workspace_id)+ if tenant is None:+ raise WorkspaceNotFoundError()+ snapshot = self._account_snapshot(session, tenant, account_id)+ tenant.name = name+ return replace(snapshot, name=name)++ @override+ def update_custom_config(+ self, *, workspace_id: str, account_id: str, changes: WorkspaceCustomConfig+ ) -> WorkspaceSnapshot:+ with self._session_factory.begin() as session:+ tenant = session.get(Tenant, workspace_id)+ if tenant is None:+ raise WorkspaceNotFoundError()+ snapshot = self._account_snapshot(session, tenant, account_id)+ tenant.custom_config_dict = {+ "remove_webapp_brand": changes.remove_webapp_brand,+ "replace_webapp_logo": changes.replace_webapp_logo,+ }+ return replace(snapshot, custom_config=changes)diff --git a/api/repositories/workspace_member_query_repository.py b/api/repositories/workspace_member_query_repository.pydeleted file mode 100644index f53e6ad1375..00000000000--- a/api/repositories/workspace_member_query_repository.py+++ /dev/null@@ -1,76 +0,0 @@-"""Database repository for the workspace-member read model."""--from typing import override--from sqlalchemy import select-from sqlalchemy.orm import Session, sessionmaker--from models.account import Account, TenantAccountJoin-from services.workspace_member_query_service import WorkspaceMemberQuery, WorkspaceMemberRecord---class WorkspaceMemberQueryRepository(WorkspaceMemberQuery):- def __init__(self, session_factory: sessionmaker[Session]) -> None:- self._session_factory = session_factory-- @override- def list_for_workspace(self, workspace_id: str) -> tuple[WorkspaceMemberRecord, ...]:- stmt = (- select(- Account.id,- Account.name,- Account.email,- Account.avatar,- Account.last_login_at,- Account.last_active_at,- Account.created_at,- Account.status,- TenantAccountJoin.role,- )- .select_from(Account)- .join(TenantAccountJoin, TenantAccountJoin.account_id == Account.id)- .where(TenantAccountJoin.tenant_id == workspace_id)- )-- with self._session_factory() as session:- rows = session.execute(stmt).all()- records = tuple(- WorkspaceMemberRecord(- id=account_id,- name=name,- email=email,- avatar=avatar,- last_login_at=last_login_at,- last_active_at=last_active_at,- created_at=created_at,- status=status.value,- legacy_role=legacy_role.value,- )- for (- account_id,- name,- email,- avatar,- last_login_at,- last_active_at,- created_at,- status,- legacy_role,- ) in rows- )-- return records-- def get_legacy_role(self, *, workspace_id: str, account_id: str) -> str | None:- """Return one member's role without loading the whole workspace roster."""-- with self._session_factory() as session:- role = session.scalar(- select(TenantAccountJoin.role)- .where(- TenantAccountJoin.tenant_id == workspace_id,- TenantAccountJoin.account_id == account_id,- )- .limit(1)- )- return role.value if role is not None else Nonediff --git a/api/repositories/workspace_query_repository.py b/api/repositories/workspace_query_repository.pydeleted file mode 100644index 12de7805b23..00000000000--- a/api/repositories/workspace_query_repository.py+++ /dev/null@@ -1,132 +0,0 @@-"""Database repository for the workspace-list read model."""--from typing import override--from sqlalchemy import select-from sqlalchemy.orm import Session, sessionmaker--from models.account import Tenant, TenantAccountJoin, TenantStatus-from services.account_login_service import ConsoleAuthWorkspaceQuery-from services.account_ports import AccountWorkspaceMembershipQuery, AccountWorkspaceSnapshotQuery-from services.entities.account_access_entities import AccountWorkspaceSnapshot-from services.oauth_device_application_service import DeviceWorkspaceQuery-from services.oauth_device_contracts import DeviceWorkspace-from services.workspace_query_service import WorkspaceQuery, WorkspaceRecord---class WorkspaceQueryRepository(- WorkspaceQuery,- AccountWorkspaceMembershipQuery,- AccountWorkspaceSnapshotQuery,- ConsoleAuthWorkspaceQuery,- DeviceWorkspaceQuery,-):- def __init__(self, session_factory: sessionmaker[Session]) -> None:- self._session_factory = session_factory-- def get_account_role(self, *, account_id: str, tenant_id: str) -> str | None:- """Read the current membership role without loading or mutating an Account."""- stmt = (- select(TenantAccountJoin.role)- .where(TenantAccountJoin.account_id == account_id, TenantAccountJoin.tenant_id == tenant_id)- .limit(1)- )- with self._session_factory() as session:- role = session.scalar(stmt)- return role.value if role is not None else None-- @override- def list_for_account(self, account_id: str) -> tuple[WorkspaceRecord, ...]:- stmt = (- select(- Tenant.id,- Tenant.name,- Tenant.status,- Tenant.created_at,- TenantAccountJoin.last_opened_at,- )- .join(TenantAccountJoin, TenantAccountJoin.tenant_id == Tenant.id)- .where(- TenantAccountJoin.account_id == account_id,- Tenant.status == TenantStatus.NORMAL,- )- .order_by(Tenant.created_at.asc())- )-- with self._session_factory() as session:- rows = session.execute(stmt).all()- return tuple(- WorkspaceRecord(- id=workspace_id,- name=name,- status=status.value,- created_at=created_at,- last_opened_at=last_opened_at,- )- for workspace_id, name, status, created_at, last_opened_at in rows- )-- @override- def list_ids_for_account(self, account_id: str) -> tuple[str, ...]:- 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 list_account_access_workspaces(self, account_id: str) -> tuple[AccountWorkspaceSnapshot, ...]:- """List every membership for the OpenAPI account identity response.-- Unlike the Console workspace picker, the identity response preserves- its existing behavior of including archived memberships.- """- stmt = (- select(- Tenant.id,- Tenant.name,- TenantAccountJoin.role,- TenantAccountJoin.current,- )- .join(TenantAccountJoin, TenantAccountJoin.tenant_id == Tenant.id)- .where(TenantAccountJoin.account_id == account_id)- .order_by(Tenant.created_at.asc(), Tenant.id.asc())- )- with self._session_factory() as session:- return tuple(- AccountWorkspaceSnapshot(- id=workspace_id,- name=name,- role=role.value,- current=current,- )- for workspace_id, name, role, current in session.execute(stmt).all()- )-- @override- def list_for_device_flow(self, account_id: str) -> tuple[DeviceWorkspace, ...]:- return tuple(- DeviceWorkspace(- id=workspace.id,- name=workspace.name,- role=workspace.role,- current=workspace.current,- )- for workspace in self.list_account_access_workspaces(account_id)- )-- @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 None-- @override- def has_active_membership(self, account_id: str) -> bool:- return self.has_active_for_account(account_id)diff --git a/api/schedule/clean_unused_datasets_task.py b/api/schedule/clean_unused_datasets_task.pyindex ef55110271e..9b4ae74070c 100644--- a/api/schedule/clean_unused_datasets_task.py+++ b/api/schedule/clean_unused_datasets_task.py@@ -9,7 +9,7 @@ from sqlalchemy.exc import SQLAlchemyErrorimport appfrom configs import dify_configfrom core.db.session_factory import session_factory-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom enums import CloudPlanfrom extensions.ext_redis import redis_clientfrom libs.pagination import paginate_querydiff --git a/api/services/account/__init__.py b/api/services/account/__init__.pynew file mode 100644index 00000000000..4f14980beaa--- /dev/null+++ b/api/services/account/__init__.py@@ -0,0 +1 @@+"""Account application services, shared contracts and infrastructure adapters."""diff --git a/api/services/account_adapters.py b/api/services/account/adapters.pysimilarity index 80%rename from api/services/account_adapters.pyrename to api/services/account/adapters.pyindex 2dd2689e7a4..b72e244c00d 100644--- a/api/services/account_adapters.py+++ b/api/services/account/adapters.py@@ -1,16 +1,28 @@"""Infrastructure adapters shared by account application services."""+import loggingimport secrets+import uuidfrom collections.abc import Sequence-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom hashlib import sha256from typing import overridefrom pydantic import TypeAdapter, ValidationError+from redis import RedisError+from sqlalchemy.orm import Session, sessionmaker+from werkzeug.exceptions import Unauthorized+from configs import dify_config+from enums import DeploymentEditionfrom extensions.ext_redis import RedisClientWrapper+from libs.datetime_utils import naive_utc_nowfrom libs.helper import RateLimiter, TokenManager+from libs.helper import timezone as validate_timezonefrom libs.workspace_permission import check_workspace_member_invite_permission+from models.account import Account, AccountStatus+from repositories.account.repository import SQLAlchemyAccountRepository+from services.account.login_adapters import DeploymentConsoleAuthPolicyGatewayfrom services.account_activation_service import (AccountActivationEligibility,InvitationTokenStore,@@ -38,6 +50,7 @@ from services.account_ports import (from services.account_security_gateway import RedisAccountEmailSecurityGatewayfrom services.billing_service import BillingServicefrom services.enterprise.account_deletion_sync import sync_account_deletion_memberships+from services.enterprise.enterprise_service import try_join_default_workspacefrom services.entities.account_activation_entities import InvitationLookup, InvitationTokenfrom services.entities.account_entities import (AccountChangeEmailNewEmailToken,@@ -59,10 +72,13 @@ from services.entities.auth_entities import (ChangeEmailOldEmailVerifiedToken,ChangeEmailTokenData,)+from services.telemetry_service import CommunityTelemetryServicefrom tasks.delete_account_task import delete_account_taskfrom tasks.mail_account_deletion_task import send_account_deletion_verification_codefrom tasks.mail_change_mail_task import send_change_mail_completed_notification_task, send_change_mail_task+logger = logging.getLogger(__name__)+_invitation_token_adapter = TypeAdapter(InvitationToken)_change_email_token_adapter: TypeAdapter[ChangeEmailTokenData] = TypeAdapter(ChangeEmailTokenData)@@ -70,12 +86,88 @@ _CHANGE_EMAIL_RATE_LIMIT_ATTEMPTS = 1_CHANGE_EMAIL_RATE_LIMIT_SECONDS = 60_ACCOUNT_DELETION_RATE_LIMIT_ATTEMPTS = 1_ACCOUNT_DELETION_RATE_LIMIT_SECONDS = 60+_ACCOUNT_LAST_ACTIVE_REFRESH_INTERVAL = timedelta(minutes=10)+++class AccountIdentityGateway:+ """Materialize framework identities while the repositories own their Sessions."""++ def __init__(+ self,+ *,+ accounts: SQLAlchemyAccountRepository,+ redis: RedisClientWrapper,+ ) -> None:+ self._accounts = accounts+ self._redis = redis++ def get_account_by_id(self, account_id: str) -> Account | None:+ return self._accounts.get_model(account_id)++ def get_account_by_email(self, email: str, *, case_fallback: bool = False) -> Account | None:+ return self._accounts.find_identity(email, case_fallback=case_fallback)++ def load_user(self, account_id: str) -> Account | None:+ now = naive_utc_now()+ account = self._accounts.load_identity(account_id, now=now)+ if account is None:+ return None+ if account.status == AccountStatus.BANNED:+ raise Unauthorized("Account is banned.")+ before = now - _ACCOUNT_LAST_ACTIVE_REFRESH_INTERVAL+ if account.last_active_at < before:+ try:+ should_refresh = self._redis.set(+ f"account_last_active_refresh:{account_id}",+ 1,+ ex=int(_ACCOUNT_LAST_ACTIVE_REFRESH_INTERVAL.total_seconds()),+ nx=True,+ )+ except RedisError:+ should_refresh = True+ if should_refresh:+ self._accounts.touch_activity(account_id, now=now, before=before, touch_updated_at=True)+ account.last_active_at = now+ return account+++class DeploymentAccountLifecyclePolicy(DeploymentConsoleAuthPolicyGateway):+ def __init__(self) -> None:+ super().__init__(billing_enabled=dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD)++ def validate_timezone(self, timezone: str) -> str:+ return validate_timezone(timezone)++ def try_join_default_workspace(self, account_id: str) -> None:+ if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.ENTERPRISE:+ try_join_default_workspace(account_id)+++class InstallationTelemetryGateway:+ def __init__(self, *, session_factory: sessionmaker[Session]) -> None:+ self._session_factory = session_factory++ def report(self) -> None:+ try:+ with self._session_factory() as session:+ CommunityTelemetryService.report_install(session=session)+ except Exception:+ logger.debug("Failed to report install telemetry", exc_info=True)class RedisInvitationTokenStore(InvitationTokenStore):def __init__(self, *, redis: RedisClientWrapper) -> None:self._redis = redis+ def create(self, invitation: InvitationToken) -> str:+ token = str(uuid.uuid4())+ self._redis.setex(+ self._invitation_token_key(token),+ dify_config.INVITE_EXPIRY_HOURS * 60 * 60,+ _invitation_token_adapter.dump_json(invitation),+ )+ return token+@overridedef find(self, invitation: InvitationLookup) -> InvitationToken | None:if invitation.workspace_id is not None and invitation.email is not None:diff --git a/api/services/account/contracts.py b/api/services/account/contracts.pynew file mode 100644index 00000000000..9f2b08def64--- /dev/null+++ b/api/services/account/contracts.py@@ -0,0 +1,37 @@+"""Account lifecycle data shared by application and persistence boundaries."""++from dataclasses import dataclass, field+from datetime import datetime+from uuid import uuid4++from services.entities.account_entities import AccountPasswordDigest+++@dataclass(frozen=True, slots=True)+class AccountCreation:+ email: str+ name: str+ interface_language: str+ interface_theme: str+ timezone: str+ password: AccountPasswordDigest | None = None+ ip_address: str | None = None+ check_normalized_email: bool = False+ status: str = "active"+ initialized_at: datetime | None = None+ id: str = field(default_factory=lambda: str(uuid4()))+++@dataclass(frozen=True, slots=True)+class SetupInput:+ email: str+ name: str+ password: str+ ip_address: str+ language: str | None+++@dataclass(frozen=True, slots=True)+class SetupStatus:+ completed: bool+ setup_at: datetime | None = Nonediff --git a/api/services/account_email_registration_adapters.py b/api/services/account/email_registration_adapters.pysimilarity index 51%rename from api/services/account_email_registration_adapters.pyrename to api/services/account/email_registration_adapters.pyindex 5bd25b33b6e..a67d10f693b 100644--- a/api/services/account_email_registration_adapters.py+++ b/api/services/account/email_registration_adapters.py@@ -1,16 +1,12 @@"""Infrastructure adapters for account email registration."""-import loggingimport secretsfrom typing import override-from redis import RedisError-from sqlalchemy.orm import Session, sessionmaker-+from configs import dify_configfrom extensions.ext_redis import RedisClientWrapperfrom libs.helper import RateLimiter, TokenManager-from models.account import Account-from services.account_email_registration_service import (+from services.account.email_registration_service import (AccountRegistrationGateway,AccountRegistrationPolicyGateway,EmailRegistrationCodeGenerator,@@ -19,27 +15,25 @@ from services.account_email_registration_service import (EmailRegistrationSendLimiter,EmailRegistrationTokenGateway,)+from services.account.login_service import ConsoleAuthSecurityGateway+from services.account.service import AccountServicefrom services.account_errors import (AccountEmailDomainSuspendedError,AccountEmailFrozenError,AccountNormalizedEmailAlreadyInUseError,+ AccountRegisterError,EmailRegistrationSeatsLimitError,+ SeatsLimitExceededError,)-from services.account_service import AccountService+from services.account_security_gateway import RedisAccountEmailSecurityGatewayfrom services.billing_service import BillingServicefrom services.entities.account_entities import (AccountEmailRegistrationPhase,AccountEmailRegistrationToken,AccountSessionTokens,)-from services.errors.account import (- AccountNormalizedEmailAlreadyInUseError as AccountNormalizedEmailAlreadyInUseServiceError,-)-from services.errors.account import AccountRegisterError, EmailDomainSuspendedError, SeatsLimitExceededErrorfrom tasks.mail_register_task import send_email_register_mail_task, send_email_register_mail_task_when_account_exist-logger = logging.getLogger(__name__)-class TokenManagerEmailRegistrationTokenGateway(EmailRegistrationTokenGateway):@override@@ -115,56 +109,27 @@ class RateLimiterEmailRegistrationSendLimiter(EmailRegistrationSendLimiter):return int(self._rate_limiter.time_window / 60)-class RedisEmailRegistrationSecurityGateway(EmailRegistrationSecurityGateway):+class RedisEmailRegistrationSecurityGateway(RedisAccountEmailSecurityGateway, EmailRegistrationSecurityGateway):def __init__(self,*,redis: RedisClientWrapper,+ login_security: ConsoleAuthSecurityGateway,verification_failure_limit: int,verification_lockout_duration: int,) -> None:- self._redis = redis- self._verification_failure_limit = verification_failure_limit- self._verification_lockout_duration = verification_lockout_duration-- @override- def is_ip_limited(self, ip_address: str) -> bool:- return AccountService.is_email_send_ip_limit(ip_address) is True-- @override- def is_verification_limited(self, email: str) -> bool:- try:- count = self._redis.get(self._verification_key(email))- return count is not None and int(count) > self._verification_failure_limit- except RedisError:- logger.warning("Failed to read email-registration verification limit", exc_info=True)- return False-- @override- def record_verification_failure(self, email: str) -> None:- try:- key = self._verification_key(email)- count = int(self._redis.get(key) or 0) + 1- self._redis.setex(key, self._verification_lockout_duration, count)- except RedisError:- logger.warning("Failed to record email-registration verification failure", exc_info=True)- return None-- @override- def reset_verification_failures(self, email: str) -> None:- try:- self._redis.delete(self._verification_key(email))- except RedisError:- logger.warning("Failed to reset email-registration verification failures", exc_info=True)- return None+ super().__init__(+ redis=redis,+ email_send_ip_limit_per_minute=dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE,+ verification_failure_limit=verification_failure_limit,+ verification_lockout_duration=verification_lockout_duration,+ verification_key_prefix="email_register_error_rate_limit",+ )+ self._login_security = login_security@overridedef reset_login_failures(self, email: str) -> None:- AccountService.reset_login_error_rate_limit(email)-- @staticmethod- def _verification_key(email: str) -> str:- return f"email_register_error_rate_limit:{email}"+ self._login_security.reset_login_failures(email)class BillingAccountRegistrationPolicyGateway(AccountRegistrationPolicyGateway):@@ -178,53 +143,32 @@ class BillingAccountRegistrationPolicyGateway(AccountRegistrationPolicyGateway):return BillingService.get_email_freeze_type(email)-class AccountServiceRegistrationGateway(AccountRegistrationGateway):- """Compatibility adapter around account provisioning and login internals."""-- def __init__(self, *, session_factory: sessionmaker[Session]) -> None:- self._session_factory = session_factory+class AccountLifecycleRegistrationGateway(AccountRegistrationGateway):+ def __init__(self, *, accounts: AccountService) -> None:+ self._accounts = accounts@overridedef create(- self,- *,- email: str,- password: str,- interface_language: str,- timezone: str | None,- ip_address: str,+ self, *, email: str, password: str, interface_language: str, timezone: str | None, ip_address: str) -> str:- with self._session_factory() as session:- try:- account = AccountService.create_account_and_tenant(- email=email,- name=email,- password=password,- interface_language=interface_language,- timezone=timezone,- ip_address=ip_address,- check_normalized_email=True,- session=session,- )- except SeatsLimitExceededError as exc:- raise EmailRegistrationSeatsLimitError from exc- except EmailDomainSuspendedError as exc:- raise AccountEmailDomainSuspendedError from exc- except AccountNormalizedEmailAlreadyInUseServiceError as exc:- raise AccountNormalizedEmailAlreadyInUseError from exc- except AccountRegisterError as exc:- raise AccountEmailFrozenError from exc- return account.id+ try:+ account = self._accounts.create_account_and_tenant(+ email=email,+ name=email,+ password=password,+ interface_language=interface_language,+ timezone=timezone,+ ip_address=ip_address,+ check_normalized_email=True,+ )+ except SeatsLimitExceededError as exc:+ raise EmailRegistrationSeatsLimitError from exc+ except (AccountEmailDomainSuspendedError, AccountNormalizedEmailAlreadyInUseError):+ raise+ except AccountRegisterError as exc:+ raise AccountEmailFrozenError from exc+ return account.id@overridedef login(self, account_id: str, *, ip_address: str) -> AccountSessionTokens:- with self._session_factory() as session:- account = session.get(Account, account_id)- if account is None:- raise RuntimeError("newly registered account no longer exists")- token_pair = AccountService.login(account=account, session=session, ip_address=ip_address)- return AccountSessionTokens(- access_token=token_pair.access_token,- refresh_token=token_pair.refresh_token,- csrf_token=token_pair.csrf_token,- )+ return self._accounts.login(account_id, ip_address=ip_address)diff --git a/api/services/account_email_registration_service.py b/api/services/account/email_registration_service.pysimilarity index 100%rename from api/services/account_email_registration_service.pyrename to api/services/account/email_registration_service.pydiff --git a/api/services/account_forgot_password_adapters.py b/api/services/account/forgot_password_adapters.pysimilarity index 99%rename from api/services/account_forgot_password_adapters.pyrename to api/services/account/forgot_password_adapters.pyindex 563db184cef..8882ffbd8ec 100644--- a/api/services/account_forgot_password_adapters.py+++ b/api/services/account/forgot_password_adapters.py@@ -9,7 +9,7 @@ from pydantic import TypeAdapter, ValidationErrorfrom extensions.ext_redis import RedisClientWrapperfrom extensions.redis_names import serialize_redis_namefrom libs.helper import RateLimiter-from services.account_forgot_password_service import (+from services.account.forgot_password_service import (FORGOT_PASSWORD_SEND_RATE_LIMIT_MAX_ATTEMPTS,FORGOT_PASSWORD_SEND_RATE_LIMIT_PREFIX,FORGOT_PASSWORD_SEND_RATE_LIMIT_WINDOW_SECONDS,diff --git a/api/services/account_forgot_password_service.py b/api/services/account/forgot_password_service.pysimilarity index 98%rename from api/services/account_forgot_password_service.pyrename to api/services/account/forgot_password_service.pyindex ea082aab45f..c0a76c4bedc 100644--- a/api/services/account_forgot_password_service.py+++ b/api/services/account/forgot_password_service.py@@ -104,12 +104,15 @@ class AccountForgotPasswordService:email: str,language: str,ip_address: str,+ require_account: bool = False,) -> str:if self._security.is_ip_limited(ip_address):raise ForgotPasswordSendIPLimitedErrornormalized_email = email.lower()account = self._accounts.find_by_email(email)+ if require_account and account is None:+ raise AccountNotFoundErrordestination = account.email if account is not None else normalized_emailregistration_allowed = self._registration.is_registration_allowed()if self._send_limits.is_limited(destination):diff --git a/api/services/account_login_adapters.py b/api/services/account/login_adapters.pysimilarity index 54%rename from api/services/account_login_adapters.pyrename to api/services/account/login_adapters.pyindex 412380d4922..21101701de7 100644--- a/api/services/account_login_adapters.py+++ b/api/services/account/login_adapters.py@@ -5,37 +5,18 @@ import secretsfrom datetime import UTC, datetime, timedeltafrom 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_createdfrom extensions.ext_redis import RedisClientWrapperfrom libs.datetime_utils import naive_utc_nowfrom libs.helper import RateLimiter, TokenManager-from libs.key_providers import generate_key_pairfrom libs.passport import PassportServicefrom libs.token import generate_csrf_token-from models import TenantCreditPoolfrom models.account import (- Account,AccountStatus,- Tenant,- TenantAccountJoin,- TenantAccountRole,- TenantPluginAutoUpgradeCategory,- TenantPluginAutoUpgradeMode,- TenantPluginAutoUpgradeStrategy,- TenantStatus,)-from models.enums import ProviderQuotaType+from repositories.account.repository import SQLAlchemyAccountRepositoryfrom 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,+from services.account.login_service import (AccountRefreshPreparationGateway,AccountSessionGateway,ConsoleAuthAuditGateway,@@ -45,20 +26,15 @@ from services.account_login_service import (EmailCodeGateway,HumanVerificationGateway,ResetPasswordEmailGateway,- WorkspaceProvisioningGateway,)+from services.account_activation_service import AccountActivationRepository, InvitationTokenStore+from services.account_security_gateway import RedisAccountEmailSecurityGatewayfrom services.billing_service import BillingServicefrom services.email_code_login_challenge import EmailCodeLoginChallengeStore, EmailCodeLoginChallengeUnavailableError-from services.enterprise.rbac_service import ListOption, RBACServicefrom services.entities.account_activation_entities import InvitationLookup-from services.entities.account_login_entities import (- AuthTokenPair,- EmailCodeChallengeStatus,- LoginInvitation,- RefreshAccountStatus,-)+from services.entities.account_entities import AccountSessionTokens+from services.entities.account_login_entities import EmailCodeChallengeStatus, LoginInvitation, RefreshAccountStatusfrom services.entities.auth_audit_entities import LoginFailureReason-from services.plugin.plugin_auto_upgrade_service import PluginAutoUpgradeServicefrom services.system_feature_service import SystemFeatureServicefrom services.turnstile_service import (EMAIL_CODE_SEND_ACTION,@@ -80,7 +56,6 @@ _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@@ -135,58 +110,31 @@ class DeploymentConsoleAuthPolicyGateway(ConsoleAuthPolicyGateway):return SystemFeatureService.get_license().seats.is_available()-class RedisConsoleAuthSecurityGateway(ConsoleAuthSecurityGateway):+class RedisConsoleAuthSecurityGateway(RedisAccountEmailSecurityGateway, ConsoleAuthSecurityGateway):def __init__(self, *, redis: RedisClientWrapper) -> None:- self._redis = redis+ super().__init__(+ redis=redis,+ email_send_ip_limit_per_minute=dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE,+ verification_failure_limit=_LOGIN_FAILURE_LIMIT,+ verification_lockout_duration=dify_config.LOGIN_LOCKOUT_DURATION,+ verification_key_prefix="login_error_rate_limit",+ )@overridedef 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+ return self.is_verification_limited(email)@overridedef 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+ self.record_verification_failure(email)@overridedef reset_login_failures(self, email: str) -> None:- try:- self._redis.delete(f"{_LOGIN_FAILURE_PREFIX}{email}")- except RedisError:- return None+ self.reset_verification_failures(email)@overridedef 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+ return self.is_ip_limited(ip_address)class TurnstileHumanVerificationGateway(HumanVerificationGateway):@@ -212,7 +160,7 @@ class RedisAccountSessionGateway(AccountSessionGateway):self._redis = redis@override- def issue(self, account_id: str) -> AuthTokenPair:+ def issue(self, account_id: str) -> AccountSessionTokens:return self._issue(account_id)@override@@ -227,11 +175,11 @@ class RedisAccountSessionGateway(AccountSessionGateway):return account_id.decode("utf-8") if account_id else None@override- def rotate(self, *, refresh_token: str, account_id: str) -> AuthTokenPair:+ def rotate(self, *, refresh_token: str, account_id: str) -> AccountSessionTokens:self._delete_refresh_token(refresh_token, account_id)return self._issue(account_id)- def _issue(self, account_id: str) -> AuthTokenPair:+ def _issue(self, account_id: str) -> AccountSessionTokens:expires_at = datetime.now(UTC) + timedelta(minutes=dify_config.ACCESS_TOKEN_EXPIRE_MINUTES)access_token = PassportService().issue({@@ -243,7 +191,7 @@ class RedisAccountSessionGateway(AccountSessionGateway):)refresh_token = secrets.token_hex(64)self._store_refresh_token(refresh_token, account_id)- return AuthTokenPair(+ return AccountSessionTokens(access_token=access_token,refresh_token=refresh_token,csrf_token=generate_csrf_token(account_id),@@ -268,187 +216,24 @@ class RedisAccountSessionGateway(AccountSessionGateway):class SQLAlchemyAccountRefreshPreparationGateway(AccountRefreshPreparationGateway):- def __init__(self, *, session_factory: sessionmaker[Session]) -> None:- self._session_factory = session_factory+ def __init__(self, *, accounts: SQLAlchemyAccountRepository) -> None:+ self._accounts = accounts@overridedef 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 = self._accounts.load_identity(account_id, now=now)+ if account is None:+ return RefreshAccountStatus.NOT_FOUND+ if account.status == AccountStatus.BANNED:+ return RefreshAccountStatus.BANNED+ self._accounts.touch_activity(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 role.id- raise ValueError(f"Builtin RBAC owner role not found in tenant {tenant_id}")+ now=now,+ before=now - _ACCOUNT_LAST_ACTIVE_REFRESH_INTERVAL,+ touch_updated_at=False,+ )+ return RefreshAccountStatus.READYclass RedisEmailCodeGateway(EmailCodeGateway):diff --git a/api/services/account_login_service.py b/api/services/account/login_service.pysimilarity index 96%rename from api/services/account_login_service.pyrename to api/services/account/login_service.pyindex 616546a21cb..6403b86b40a 100644--- a/api/services/account_login_service.py+++ b/api/services/account/login_service.py@@ -7,9 +7,9 @@ from typing import Never, Protocolfrom constants.languages import get_valid_language, language_timezone_mappingfrom services import account_errorsfrom services.account_ports import AccountPasswordHasher+from services.entities.account_entities import AccountSessionTokensfrom services.entities.account_login_entities import (AccountSessionPreparation,- AuthTokenPair,EmailCodeChallengeStatus,EmailCodeLoginCommand,EmailCodeSendCommand,@@ -69,13 +69,13 @@ class HumanVerificationGateway(Protocol):class AccountSessionGateway(Protocol):- def issue(self, account_id: str) -> AuthTokenPair: ...+ def issue(self, account_id: str) -> AccountSessionTokens: ...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: ...+ def rotate(self, *, refresh_token: str, account_id: str) -> AccountSessionTokens: ...class AccountRefreshPreparationGateway(Protocol):@@ -95,7 +95,7 @@ class AccountProvisioningGateway(Protocol):class WorkspaceProvisioningGateway(Protocol):- def create_owner_workspace(self, account_id: str) -> None: ...+ def ensure_owner_workspace(self, account_id: str) -> None: ...class EmailCodeGateway(Protocol):@@ -201,15 +201,15 @@ class ConsoleAuthenticationService: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)+ return PasswordLoginResult(tokens=None, workspace_found=False)- token_pair = self._issue_session(+ tokens = 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)+ return PasswordLoginResult(tokens=tokens, workspace_found=True)def logout(self, account_id: str) -> None:self._sessions.revoke(account_id)@@ -250,7 +250,7 @@ class ConsoleAuthenticationService:language=self._email_language(command.language),)- def login_with_email_code(self, command: EmailCodeLoginCommand) -> AuthTokenPair:+ def login_with_email_code(self, command: EmailCodeLoginCommand) -> AccountSessionTokens:normalized_email = command.email.lower()if not self._is_valid_email_code(command.code):self._fail(@@ -279,7 +279,7 @@ class ConsoleAuthenticationService:raise account_errors.LoginWorkspaceLimitErrorif not self._policies.is_workspace_creation_allowed():raise account_errors.LoginWorkspaceCreationNotAllowedError- self._workspace_provisioning.create_owner_workspace(account.id)+ self._workspace_provisioning.ensure_owner_workspace(account.id)account_id = account.idelse:if not self._policies.is_registration_allowed():@@ -299,15 +299,15 @@ class ConsoleAuthenticationService:ip_address=command.ip_address,)- token_pair = self._issue_session(+ tokens = 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+ return tokens- def refresh(self, refresh_token: str) -> AuthTokenPair:+ def refresh(self, refresh_token: str) -> AccountSessionTokens:account_id = self._sessions.resolve_refresh_token(refresh_token)if account_id is None:raise account_errors.InvalidRefreshTokenError("Invalid refresh token")@@ -362,7 +362,7 @@ class ConsoleAuthenticationService:account_id: str,ip_address: str,activate_pending_account: bool,- ) -> AuthTokenPair:+ ) -> AccountSessionTokens:prepared = self._accounts.prepare_session(account_id,AccountSessionPreparation(diff --git a/api/services/account_oauth_adapters.py b/api/services/account/oauth_adapters.pysimilarity index 64%rename from api/services/account_oauth_adapters.pyrename to api/services/account/oauth_adapters.pyindex c9586958311..730b8f234a5 100644--- a/api/services/account_oauth_adapters.py+++ b/api/services/account/oauth_adapters.py@@ -13,21 +13,45 @@ from redis.exceptions import LockErrorfrom extensions.ext_redis import RedisClientWrapperfrom libs.oauth import OAuth-from services.account_errors import (- OAuthIdentityLockUnavailableError,- OAuthProviderAuthorizationError,- OAuthProviderRequestError,-)-from services.account_oauth_service import (+from services.account.oauth_service import (OAuthAccountClaimLease,OAuthAccountClaimLock,+ OAuthAccountRegistrationGateway,+ OAuthInvitationGateway,OAuthProviderGateway,OAuthRegistrationPolicyGateway,+ OAuthSessionGateway,+ OAuthWorkspaceGateway,OAuthWorkspacePolicyGateway,)+from services.account.service import AccountService+from services.account_activation_service import AccountActivationRepository, InvitationTokenStore+from services.account_errors import (+ AccountEmailDomainSuspendedError,+ AccountNotFoundError,+ AccountRegisterError,+ OAuthAccountNotFoundError,+ OAuthIdentityLockUnavailableError,+ OAuthProviderAuthorizationError,+ OAuthProviderRequestError,+ OAuthRegistrationError,+ OAuthSeatsLimitExceededError,+ OAuthWorkspaceCreationNotAllowedError,+ SeatsLimitExceededError,+)from services.billing_service import BillingService-from services.entities.account_oauth_entities import OAuthAuthorizationRequest, OAuthIdentity+from services.enterprise.enterprise_service import try_join_default_workspace+from services.entities.account_activation_entities import InvitationLookup+from services.entities.account_entities import AccountSessionTokens+from services.entities.account_oauth_entities import (+ OAuthAccountRegistration,+ OAuthAuthorizationRequest,+ OAuthIdentity,+ OAuthInvitation,+)+from services.errors.workspace import WorkSpaceNotAllowedCreateError, WorkspacesLimitExceededErrorfrom services.system_feature_service import SystemFeatureService+from services.workspace.provisioning_service import WorkspaceProvisioningServicelogger = logging.getLogger(__name__)@@ -201,3 +225,73 @@ class DeploymentOAuthPolicyGateway(OAuthRegistrationPolicyGateway, OAuthWorkspac@overridedef is_creation_allowed(self) -> bool:return SystemFeatureService.is_workspace_creation_allowed()+++class AccountActivationOAuthInvitationGateway(OAuthInvitationGateway):+ def __init__(self, *, tokens: InvitationTokenStore, accounts: AccountActivationRepository) -> None:+ self._tokens = tokens+ self._accounts = accounts++ def resolve(self, invite_token: str) -> OAuthInvitation | None:+ token = self._tokens.find(InvitationLookup(workspace_id=None, email=None, token=invite_token))+ if token is None:+ return None+ invitation = self._accounts.resolve(token)+ if invitation is None:+ return None+ return OAuthInvitation(invitation.account_id, invitation.account_email, invitation.account_status)+++class AccountLifecycleOAuthRegistrationGateway(OAuthAccountRegistrationGateway):+ def __init__(self, *, accounts: AccountService) -> None:+ self._accounts = accounts++ def register(self, registration: OAuthAccountRegistration) -> str:+ try:+ account = self._accounts.create_account(+ email=registration.email,+ name=registration.name,+ interface_language=registration.language,+ password=None,+ timezone=registration.timezone,+ ip_address=registration.ip_address,+ check_normalized_email=True,+ status="active",+ initialized=True,+ )+ except AccountEmailDomainSuspendedError:+ raise+ except SeatsLimitExceededError as exc:+ raise OAuthSeatsLimitExceededError from exc+ except AccountRegisterError as exc:+ raise OAuthRegistrationError(exc.description) from exc+ except Exception as exc:+ raise OAuthRegistrationError(f"Registration failed: {exc}") from exc+ return account.id+++class WorkspaceProvisioningOAuthGateway(OAuthWorkspaceGateway):+ def __init__(self, *, workspaces: WorkspaceProvisioningService) -> None:+ self._workspaces = workspaces++ def create_owner_workspace(self, account_id: str) -> None:+ try:+ self._workspaces.create_owner_workspace(account_id)+ except AccountNotFoundError as exc:+ raise OAuthAccountNotFoundError from exc+ except (WorkSpaceNotAllowedCreateError, WorkspacesLimitExceededError) as exc:+ raise OAuthWorkspaceCreationNotAllowedError from exc++ def try_join_default_workspace(self, account_id: str) -> None:+ try_join_default_workspace(account_id)+++class AccountLifecycleOAuthSessionGateway(OAuthSessionGateway):+ def __init__(self, *, accounts: AccountService) -> None:+ self._accounts = accounts++ def login(self, account_id: str, *, ip_address: str) -> AccountSessionTokens:+ try:+ return self._accounts.login(account_id, ip_address=ip_address)+ except AccountNotFoundError as exc:+ raise OAuthAccountNotFoundError from excdiff --git a/api/services/account_oauth_service.py b/api/services/account/oauth_service.pysimilarity index 100%rename from api/services/account_oauth_service.pyrename to api/services/account/oauth_service.pydiff --git a/api/services/account/service.py b/api/services/account/service.pynew file mode 100644index 00000000000..90025b83edf--- /dev/null+++ b/api/services/account/service.py@@ -0,0 +1,292 @@+"""Account creation, registration and session use cases, independent of ORM and HTTP."""++from collections.abc import Callable+from datetime import datetime+from typing import Protocol++from constants.languages import get_valid_language, language_timezone_mapping+from services.account.contracts import AccountCreation, SetupInput+from services.account.login_service import AccountSessionGateway, ConsoleAuthSecurityGateway+from services.account_errors import (+ AccountEmailDomainSuspendedError,+ AccountLoginError,+ AccountNormalizedEmailAlreadyInUseError,+ AccountNotFoundError,+ AccountPasswordError,+ AccountRegisterError,+ SeatsLimitExceededError,+)+from services.account_ports import AccountPasswordHasher+from services.entities.account_entities import (+ AccountCredentials,+ AccountPasswordDigest,+ AccountSessionTokens,+ AccountSnapshot,+)+from services.entities.account_login_entities import AccountSessionPreparation+from services.errors.workspace import WorkSpaceNotAllowedCreateError+++class AccountLifecycleStore(Protocol):+ def get(self, account_id: str) -> AccountSnapshot | None: ...++ def find_by_email(self, email: str) -> AccountSnapshot | None: ...++ def normalized_email_exists(self, email: str) -> bool: ...++ def create(self, creation: AccountCreation) -> AccountSnapshot: ...++ def prepare_session(self, account_id: str, preparation: AccountSessionPreparation) -> bool: ...++ def get_credentials(self, account_id: str) -> AccountCredentials | None: ...++ def update_password(self, account_id: str, password: AccountPasswordDigest) -> AccountSnapshot | None: ...++ def set_email(self, account_id: str, email: str) -> None: ...+++class AccountLifecyclePolicy(Protocol):+ def is_registration_allowed(self) -> bool: ...++ def has_account_capacity(self) -> bool: ...++ def get_email_freeze_type(self, email: str) -> str | None: ...++ def is_workspace_creation_allowed(self) -> bool: ...++ def has_workspace_capacity(self) -> bool: ...++ def validate_timezone(self, timezone: str) -> str: ...++ def try_join_default_workspace(self, account_id: str) -> None: ...+++class AccountWorkspaceProvisioner(Protocol):+ def create_owner_workspace(+ self, account_id: str, *, name: str | None = None, is_setup: bool = False, if_missing: bool = False+ ) -> None: ...+++class AccountService:+ def __init__(+ self,+ *,+ accounts: AccountLifecycleStore,+ policies: AccountLifecyclePolicy,+ passwords: AccountPasswordHasher,+ workspaces: AccountWorkspaceProvisioner,+ sessions: AccountSessionGateway,+ security: ConsoleAuthSecurityGateway,+ now: Callable[[], datetime],+ ) -> None:+ self._accounts = accounts+ self._policies = policies+ self._passwords = passwords+ self._workspaces = workspaces+ self._sessions = sessions+ self._security = security+ self._now = now++ def get_account_by_id(self, account_id: str) -> AccountSnapshot | None:+ return self._accounts.get(account_id)++ def get_account_by_email_with_case_fallback(self, email: str) -> AccountSnapshot | None:+ return self._accounts.find_by_email(email)++ def authenticate(self, email: str, password: str) -> AccountSnapshot:+ account = self.get_account_by_email_with_case_fallback(email)+ if account is None:+ raise AccountNotFoundError()+ if account.status == "banned":+ raise AccountLoginError("Account is banned.")+ credentials = self._accounts.get_credentials(account.id)+ if (+ not credentials+ or not credentials.password_hash+ or not credentials.password_salt+ or not self._passwords.verify(+ password, password_hash=credentials.password_hash, password_salt=credentials.password_salt+ )+ ):+ raise AccountPasswordError("Invalid email or password.")+ return account++ def reset_login_failures(self, email: str) -> None:+ self._security.reset_login_failures(email)++ def reset_password(self, account_id: str, password: str, *, email: str) -> None:+ if self._accounts.update_password(account_id, self._passwords.hash(password)) is None:+ raise AccountNotFoundError()+ self.reset_login_failures(email)++ def set_email(self, account_id: str, email: str) -> None:+ self._accounts.set_email(account_id, email)++ def create_account(+ self,+ email: str,+ name: str,+ interface_language: str,+ password: str | None = None,+ interface_theme: str = "light",+ is_setup: bool = False,+ timezone: str | None = None,+ ip_address: str | None = None,+ check_normalized_email: bool = False,+ *,+ status: str = "active",+ initialized: bool = False,+ ) -> AccountSnapshot:+ if not self._policies.is_registration_allowed() and not is_setup:+ raise AccountNotFoundError("Account registration is disabled.")+ if check_normalized_email and self._accounts.normalized_email_exists(email):+ raise AccountNormalizedEmailAlreadyInUseError("An account with an equivalent email already exists.")+ if not self._policies.has_account_capacity():+ raise SeatsLimitExceededError("licensed seats limit exceeded")+ freeze_type = self._policies.get_email_freeze_type(email)+ if freeze_type == "email_domain_suspended":+ raise AccountEmailDomainSuspendedError()+ if freeze_type:+ raise AccountRegisterError(+ "This email account has been deleted within the past "+ "30 days and is temporarily unavailable for new account registration"+ )+ resolved_timezone = (+ self._policies.validate_timezone(timezone)+ if timezone is not None+ else language_timezone_mapping.get(interface_language, "UTC")+ )+ return self._accounts.create(+ AccountCreation(+ email=email,+ name=name,+ interface_language=interface_language,+ interface_theme=interface_theme,+ timezone=resolved_timezone,+ password=self._passwords.hash(password) if password else None,+ ip_address=ip_address,+ check_normalized_email=check_normalized_email,+ status=status,+ initialized_at=self._now() if initialized else None,+ )+ )++ def create_account_and_tenant(+ self,+ email: str,+ name: str,+ interface_language: str,+ password: str | None = None,+ timezone: str | None = None,+ ip_address: str | None = None,+ check_normalized_email: bool = False,+ ) -> AccountSnapshot:+ account = self.create_account(+ email=email,+ name=name,+ interface_language=interface_language,+ password=password,+ timezone=timezone,+ ip_address=ip_address,+ check_normalized_email=check_normalized_email,+ )+ try:+ self._workspaces.create_owner_workspace(account.id, if_missing=True)+ finally:+ self._policies.try_join_default_workspace(account.id)+ return account++ def register(+ self,+ email: str,+ name: str,+ password: str | None = None,+ language: str | None = None,+ status: str | None = None,+ is_setup: bool = False,+ create_workspace_required: bool = True,+ timezone: str | None = None,+ ip_address: str | None = None,+ check_normalized_email: bool = True,+ ) -> AccountSnapshot:+ try:+ account = self.create_account(+ email=email,+ name=name,+ interface_language=get_valid_language(language),+ password=password,+ is_setup=is_setup,+ timezone=timezone,+ ip_address=ip_address,+ check_normalized_email=check_normalized_email,+ status=status or "active",+ initialized=True,+ )+ try:+ if (+ create_workspace_required+ and self._policies.is_workspace_creation_allowed()+ and self._policies.has_workspace_capacity()+ ):+ self._workspaces.create_owner_workspace(account.id)+ finally:+ self._policies.try_join_default_workspace(account.id)+ return account+ except WorkSpaceNotAllowedCreateError as exc:+ raise AccountRegisterError("Workspace is not allowed to create.") from exc+ except (SeatsLimitExceededError, AccountRegisterError):+ raise+ except Exception as exc:+ raise AccountRegisterError(f"Registration failed: {exc}") from exc++ def login(self, account_id: str, *, ip_address: str) -> AccountSessionTokens:+ prepared = self._accounts.prepare_session(+ account_id,+ AccountSessionPreparation(logged_in_at=self._now(), ip_address=ip_address, activate_pending_account=True),+ )+ if not prepared:+ raise AccountNotFoundError()+ return self._sessions.issue(account_id)+++class InstallationStore(Protocol):+ def mark_setup(self) -> None: ...++ def reset_setup(self) -> None: ...+++class InstallationTelemetry(Protocol):+ def report(self) -> None: ...+++class AccountSetupProvisioner:+ def __init__(+ self,+ *,+ accounts: AccountService,+ workspaces: AccountWorkspaceProvisioner,+ installation: InstallationStore,+ telemetry: InstallationTelemetry,+ ) -> None:+ self._accounts = accounts+ self._workspaces = workspaces+ self._installation = installation+ self._telemetry = telemetry++ def provision(self, setup: SetupInput) -> None:+ try:+ account = self._accounts.create_account(+ email=setup.email,+ name=setup.name,+ interface_language=get_valid_language(setup.language),+ password=setup.password,+ ip_address=setup.ip_address,+ is_setup=True,+ initialized=True,+ )+ self._workspaces.create_owner_workspace(account.id, is_setup=True, if_missing=True)+ self._installation.mark_setup()+ except Exception as exc:+ self._installation.reset_setup()+ raise ValueError(f"Setup failed: {exc}") from exc+ self._telemetry.report()diff --git a/api/services/account_activation_service.py b/api/services/account_activation_service.pyindex 7d497471143..ebc1298dd48 100644--- a/api/services/account_activation_service.py+++ b/api/services/account_activation_service.py@@ -2,6 +2,12 @@from typing import Protocol+from services.account_errors import (+ AccountEmailDomainSuspendedError,+ FrozenAccountError,+ InvalidInvitationError,+ InvitationAccountMismatchError,+)from services.entities.account_activation_entities import (AccountInvitation,AccountSetup,@@ -52,22 +58,6 @@ class WorkspaceMemberAccessSync(Protocol):def sync(self, workspace_id: str, account_id: str) -> None: ...-class InvalidInvitationError(Exception):- """The invitation is invalid, stale, or missing required activation data."""---class InvitationAccountMismatchError(Exception):- """An authenticated account attempted to consume another account's invitation."""---class FrozenAccountError(Exception):- """The invited account is temporarily ineligible for activation."""---class EmailDomainSuspendedError(Exception):- """The invited account uses a suspended email domain."""--class AccountActivationService:def __init__(self,@@ -113,7 +103,7 @@ class AccountActivationService:freeze_type = self._eligibility.get_freeze_type(invitation.account_email)if freeze_type == "email_domain_suspended":- raise EmailDomainSuspendedError+ raise AccountEmailDomainSuspendedErrorif freeze_type:raise FrozenAccountErrordiff --git a/api/services/account_errors.py b/api/services/account_errors.pyindex 9ff9d5ec73a..0535bfd7305 100644--- a/api/services/account_errors.py+++ b/api/services/account_errors.py@@ -5,14 +5,46 @@ class AccountApplicationError(Exception):"""Base class for failures owned by account application services."""+class AccountRegisterError(AccountApplicationError):+ """Account registration was rejected by a lifecycle policy."""++ def __init__(self, description: str = "") -> None:+ super().__init__(description)+ self.description = description+++class AccountLoginError(AccountApplicationError):+ """The account cannot sign in."""+++class AccountPasswordError(AccountApplicationError):+ """The supplied sign-in password is incorrect."""+++class SeatsLimitExceededError(AccountApplicationError):+ """The deployment has no capacity for another account."""++class AccountNotFoundError(AccountApplicationError):- """The admitted account no longer exists."""+ """The requested account does not exist."""class AccountSessionNotFoundError(AccountApplicationError):"""The requested access session is not owned by the admitted account."""+class InvalidInvitationError(AccountApplicationError):+ """The invitation is invalid, stale, or missing required activation data."""+++class InvitationAccountMismatchError(AccountApplicationError):+ """An authenticated account attempted to consume another account's invitation."""+++class FrozenAccountError(AccountApplicationError):+ """The invited account is temporarily ineligible for activation."""++class CurrentAccountPasswordIncorrectError(AccountApplicationError):"""The supplied current password does not match the account credential."""@@ -109,15 +141,18 @@ class InvalidChangeEmailCodeError(AccountApplicationError):"""The verification code does not match the current token."""-class AccountEmailFrozenError(AccountApplicationError):+class AccountEmailFrozenError(AccountRegisterError):"""The target email is temporarily frozen by account policy."""class AccountEmailDomainSuspendedError(AccountEmailFrozenError):"""The target email belongs to a suspended domain."""+ def __init__(self, description: str = "This email domain has been suspended.") -> None:+ super().__init__(description)+-class AccountEmailAlreadyInUseError(AccountApplicationError):+class AccountEmailAlreadyInUseError(AccountRegisterError):"""The target email already belongs to an account."""diff --git a/api/services/account_service.py b/api/services/account_service.pydeleted file mode 100644index 5764229fde6..00000000000--- a/api/services/account_service.py+++ /dev/null@@ -1,2002 +0,0 @@-"""Account, workspace, and invitation services.--Database access in this module is caller-scoped: methods that read or mutate ORM state accept an explicit-``session`` so controllers, tasks, and tests can control transaction lifetime and avoid hidden Flask-scoped session-usage inside service logic.-"""--import base64-import json-import logging-import secrets-import uuid-from collections.abc import Iterator-from datetime import UTC, datetime, timedelta-from hashlib import sha256-from typing import Any, NotRequired, TypedDict--from pydantic import BaseModel, TypeAdapter, ValidationError-from sqlalchemy import Row, delete, func, select, update-from sqlalchemy.orm import Session-from werkzeug.exceptions import Unauthorized--from configs import dify_config-from constants.languages import get_valid_language, language_timezone_mapping-from enums import DeploymentEdition-from events.tenant_event import tenant_was_created-from extensions.ext_database import db-from extensions.ext_redis import redis_client, redis_fallback-from libs.datetime_utils import naive_utc_now-from libs.helper import RateLimiter, TokenManager-from libs.helper import timezone as validate_timezone-from libs.key_providers import generate_key_pair-from libs.passport import PassportService-from libs.password import hash_password, valid_password-from libs.token import generate_csrf_token-from models.account import (- Account,- AccountIntegrate,- AccountStatus,- Tenant,- TenantAccountJoin,- TenantAccountRole,- TenantPluginAutoUpgradeCategory,- TenantPluginAutoUpgradeMode,- TenantPluginAutoUpgradeStrategy,- TenantStatus,-)-from models.dataset import Dataset-from models.model import App, DifySetup-from services.account_email import normalize_email-from services.account_forgot_password_service import (- FORGOT_PASSWORD_SEND_RATE_LIMIT_MAX_ATTEMPTS,- FORGOT_PASSWORD_SEND_RATE_LIMIT_PREFIX,- FORGOT_PASSWORD_SEND_RATE_LIMIT_WINDOW_SECONDS,- FORGOT_PASSWORD_VERIFICATION_FAILURE_LIMIT,- FORGOT_PASSWORD_VERIFICATION_KEY_PREFIX,-)-from services.billing_service import BillingService-from services.enterprise.rbac_service import ListOption, RBACService-from services.entities.auth_entities import (- ChangeEmailNewEmailToken,- ChangeEmailOldEmailToken,- ChangeEmailPhase,- ChangeEmailTokenData,-)-from services.errors.account import (- AccountAlreadyInTenantError,- AccountNormalizedEmailAlreadyInUseError,- AccountNotFoundError,- AccountNotLinkTenantError,- AccountRegisterError,- CannotOperateSelfError,- EmailDomainSuspendedError,- InvalidActionError,- MemberNotInTenantError,- NoPermissionError,- RefreshTokenNotFoundError,- RoleAlreadyAssignedError,- SeatsLimitExceededError,-)-from services.errors.workspace import WorkSpaceNotAllowedCreateError, WorkspacesLimitExceededError-from services.plugin.plugin_auto_upgrade_service import PluginAutoUpgradeService-from services.system_feature_service import SystemFeatureService-from services.telemetry_service import CommunityTelemetryService-from tasks.mail_change_mail_task import (- send_change_mail_completed_notification_task,- send_change_mail_task,-)-from tasks.mail_invite_member_task import send_invite_member_mail_task-from tasks.mail_owner_transfer_task import (- send_new_owner_transfer_notify_email_task,- send_old_owner_transfer_notify_email_task,- send_owner_transfer_confirm_task,-)-from tasks.mail_reset_password_task import (- send_reset_password_mail_task,- send_reset_password_mail_task_when_account_not_exist,-)---class InvitationData(TypedDict):- account_id: str- email: str- workspace_id: str- role: NotRequired[str]- requires_setup: NotRequired[bool]---_invitation_adapter: TypeAdapter[InvitationData] = TypeAdapter(InvitationData)--logger = logging.getLogger(__name__)--_change_email_token_adapter: TypeAdapter[ChangeEmailTokenData] = TypeAdapter(ChangeEmailTokenData)---class EnterpriseWorkspaceMemberAccountNotFoundError(Exception):- pass---class EnterpriseWorkspaceMemberWorkspaceNotFoundError(Exception):- pass---class InvitationDetailDict(TypedDict):- account: Account- data: InvitationData- tenant: Tenant---def _try_join_enterprise_default_workspace(account_id: str) -> None:- """Best-effort join to enterprise default workspace."""- if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.ENTERPRISE:- return-- from services.enterprise.enterprise_service import try_join_default_workspace-- try_join_default_workspace(account_id)---class TokenPair(BaseModel):- access_token: str- refresh_token: str- csrf_token: str---REFRESH_TOKEN_PREFIX = "refresh_token:"-ACCOUNT_REFRESH_TOKEN_PREFIX = "account_refresh_token:"-REFRESH_TOKEN_EXPIRY = timedelta(days=dify_config.REFRESH_TOKEN_EXPIRE_DAYS)-ACCOUNT_LAST_ACTIVE_REFRESH_PREFIX = "account_last_active_refresh:"-ACCOUNT_LAST_ACTIVE_REFRESH_INTERVAL = timedelta(minutes=10)---class AccountService:- CHANGE_EMAIL_PHASE_OLD = ChangeEmailPhase.OLD_EMAIL- CHANGE_EMAIL_PHASE_NEW = ChangeEmailPhase.NEW_EMAIL-- reset_password_rate_limiter = RateLimiter(- prefix=FORGOT_PASSWORD_SEND_RATE_LIMIT_PREFIX,- max_attempts=FORGOT_PASSWORD_SEND_RATE_LIMIT_MAX_ATTEMPTS,- time_window=FORGOT_PASSWORD_SEND_RATE_LIMIT_WINDOW_SECONDS,- )- 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)-- LOGIN_MAX_ERROR_LIMITS = 5- CHANGE_EMAIL_MAX_ERROR_LIMITS = 5- OWNER_TRANSFER_MAX_ERROR_LIMITS = 5-- @staticmethod- def _resolve_role_id_by_tag(tenant_id: str, account_id: str, tag: str) -> str:- options = ListOption(page_number=1, results_per_page=100)- roles = RBACService.Roles.list(tenant_id, account_id, options=options).data- for rbac_role in roles:- if rbac_role.is_builtin and rbac_role.category == "global_system_default" and rbac_role.role_tag == tag:- return str(rbac_role.id)-- raise ValueError(f"Builtin RBAC role not found for tag {tag!r} in tenant {tenant_id}")-- @staticmethod- def _resolve_legacy_role_id(tenant_id: str, account_id: str, role: TenantAccountRole) -> str:- """Resolve a legacy workspace role to the corresponding RBAC role id.-- Looks up the builtin RBAC role whose tag matches the legacy role name- (e.g. ``TenantAccountRole.ADMIN`` → builtin role with tag ``"admin"``).- """- expected_tag = {- TenantAccountRole.OWNER: "owner",- TenantAccountRole.ADMIN: "admin",- TenantAccountRole.EDITOR: "editor",- TenantAccountRole.NORMAL: "normal",- TenantAccountRole.DATASET_OPERATOR: "dataset_operator",- }[role]- return AccountService._resolve_role_id_by_tag(tenant_id, account_id, expected_tag)-- @staticmethod- def get_workspace_permission_keys(tenant_id: str, account_id: str, *, session: Session) -> set[str]:- permissions = RBACService.MyPermissions.get(tenant_id, account_id, session=session)- return set(getattr(getattr(permissions, "workspace", None), "permission_keys", []) or [])-- @staticmethod- def get_rbac_workspace_owner_account_id(tenant_id: str, actor_account_id: str, *, session: Session) -> str:- """Return the account id bound to the workspace owner RBAC role."""- owner_role_id = AccountService._resolve_legacy_role_id(- tenant_id=tenant_id,- account_id=actor_account_id,- role=TenantAccountRole.OWNER,- )- owner_members = RBACService.Roles.members(- tenant_id=tenant_id,- account_id=actor_account_id,- role_id=owner_role_id,- options=ListOption(page_number=1, results_per_page=1),- ).data- if not owner_members:- raise ValueError(f"Workspace RBAC owner not found for tenant {tenant_id}.")- return owner_members[0].account_id-- @staticmethod- def is_rbac_workspace_owner(- tenant_id: str, actor_account_id: str, member_account_id: str, *, session: Session- ) -> bool:- roles = RBACService.MemberRoles.get(- tenant_id=tenant_id,- account_id=actor_account_id,- member_account_id=member_account_id,- session=session,- ).roles- return any(- role.is_builtin and role.category == "global_system_default" and role.role_tag == "owner" for role in roles- )-- @staticmethod- def _get_refresh_token_key(refresh_token: str) -> str:- return f"{REFRESH_TOKEN_PREFIX}{refresh_token}"-- @staticmethod- def _get_account_refresh_token_key(account_id: str) -> str:- return f"{ACCOUNT_REFRESH_TOKEN_PREFIX}{account_id}"-- @staticmethod- def _get_account_last_active_refresh_key(account_id: str) -> str:- return f"{ACCOUNT_LAST_ACTIVE_REFRESH_PREFIX}{account_id}"-- @staticmethod- @redis_fallback(default_return=True)- def _should_refresh_account_last_active(account_id: str) -> bool:- return bool(- redis_client.set(- AccountService._get_account_last_active_refresh_key(account_id),- 1,- ex=int(ACCOUNT_LAST_ACTIVE_REFRESH_INTERVAL.total_seconds()),- nx=True,- )- )-- @staticmethod- def _refresh_account_last_active(account: Account, session: Session) -> None:- now = naive_utc_now()- refresh_before = now - ACCOUNT_LAST_ACTIVE_REFRESH_INTERVAL-- if account.last_active_at >= refresh_before:- return-- if not AccountService._should_refresh_account_last_active(account.id):- return-- session.execute(- update(Account)- .where(Account.id == account.id, Account.last_active_at < refresh_before)- .values(last_active_at=now, updated_at=func.current_timestamp())- )- session.commit()-- @staticmethod- def _store_refresh_token(refresh_token: str, account_id: str):- redis_client.setex(AccountService._get_refresh_token_key(refresh_token), REFRESH_TOKEN_EXPIRY, account_id)- redis_client.setex(- AccountService._get_account_refresh_token_key(account_id), REFRESH_TOKEN_EXPIRY, refresh_token- )-- @staticmethod- def _delete_refresh_token(refresh_token: str, account_id: str):- redis_client.delete(AccountService._get_refresh_token_key(refresh_token))- redis_client.delete(AccountService._get_account_refresh_token_key(account_id))-- @staticmethod- def get_account_by_email(email: str, *, session: Session) -> Account | None:- """Plain ``Account`` getter keyed by case-sensitive email."""- return session.execute(select(Account).where(Account.email == email)).scalar_one_or_none()-- @staticmethod- def has_account_with_normalized_email(email: str, *, session: Session) -> bool:- """Check the normalized identity through its indexed column."""- normalized_email = normalize_email(email)- row = session.scalar(select(Account.id).where(Account.normalized_email == normalized_email).limit(1))- return row is not None-- @staticmethod- def ensure_registration_email_available(email: str, *, session: Session) -> None:- if AccountService.has_account_with_normalized_email(email, session=session):- raise AccountNormalizedEmailAlreadyInUseError("An account with an equivalent email already exists.")-- @staticmethod- def get_account_by_id(account_id: str, *, session: Session) -> Account | None:- """Plain ``Account`` getter — no banned check, no tenant rotation,- no ``last_active_at`` write. Use this from authentication and read- paths where ``load_user``'s current-tenant assignment and commit are- unwanted.-- ``session`` is injected by the caller so this service stays free- of a Flask-scoped session import.- """- return session.get(Account, account_id)-- @staticmethod- def load_user(user_id: str, session: Session) -> None | Account:- account = session.get(Account, user_id)- if not account:- return None-- if account.status == AccountStatus.BANNED:- raise Unauthorized("Account is banned.")-- current_tenant_join = session.scalar(- select(TenantAccountJoin)- .where(TenantAccountJoin.account_id == account.id, TenantAccountJoin.current == True)- .limit(1)- )- if current_tenant_join is not None:- account.set_tenant_id_with_session(current_tenant_join.tenant_id, session=session)-- has_valid_current_tenant = (- current_tenant_join is not None- and account.current_tenant is not None- and account.current_tenant.status == TenantStatus.NORMAL- )- if not has_valid_current_tenant:- if current_tenant_join is not None:- current_tenant_join.current = False-- available_tenant_join = session.scalar(- select(TenantAccountJoin)- .join(Tenant, TenantAccountJoin.tenant_id == Tenant.id)- .where(- TenantAccountJoin.account_id == account.id,- Tenant.status == TenantStatus.NORMAL,- )- .order_by(TenantAccountJoin.id.asc())- .limit(1)- )- if available_tenant_join is None:- if current_tenant_join is not None:- session.commit()- return None-- account.set_tenant_id_with_session(available_tenant_join.tenant_id, session=session)- available_tenant_join.current = True- available_tenant_join.last_opened_at = naive_utc_now()- session.commit()-- AccountService._refresh_account_last_active(account, session)- # NOTE: make sure account is accessible outside of a db session- # This ensures that it will work correctly after upgrading to Flask version 3.1.2- session.refresh(account)- if session.expire_on_commit and account.current_tenant is not None:- session.refresh(account.current_tenant)- session.close()- return account-- @staticmethod- def 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,- "exp": exp,- "iss": dify_config.DEPLOYMENT_EDITION.value,- "sub": "Console API Passport",- }-- token: str = PassportService().issue(payload)- return token-- @staticmethod- def create_account(- email: str,- name: str,- interface_language: str,- password: str | None = None,- interface_theme: str = "light",- is_setup: bool | None = False,- timezone: str | None = None,- ip_address: str | None = None,- check_normalized_email: bool = False,- *,- session: Session,- ) -> Account:- """Create an account, preferring explicit user timezone over language-derived defaults."""- if not SystemFeatureService.is_registration_allowed() and not is_setup:- raise AccountNotFoundError("Account registration is disabled.")-- if check_normalized_email:- AccountService.ensure_registration_email_available(email, session=session)-- # A licensed seat is one Account row, deployment-wide; joining an existing- # account into another workspace does not pass through here and costs no seat.- # get_license() carries the full license payload that server-side enforcement needs;- # the public system-features endpoint exposes only license status.- if not SystemFeatureService.get_license().seats.is_available():- raise SeatsLimitExceededError("licensed seats limit exceeded")-- 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"- )- )-- password_to_set = None- salt_to_set = None- if password:- valid_password(password)-- # generate password salt- salt = secrets.token_bytes(16)- base64_salt = base64.b64encode(salt).decode()-- # encrypt password with salt- password_hashed = hash_password(password, salt)- base64_password_hashed = base64.b64encode(password_hashed).decode()-- password_to_set = base64_password_hashed- salt_to_set = base64_salt-- resolved_timezone = language_timezone_mapping.get(interface_language, "UTC")- if timezone is not None:- resolved_timezone = validate_timezone(timezone)-- account = Account(- name=name,- email=email,- normalized_email=normalize_email(email),- password=password_to_set,- password_salt=salt_to_set,- interface_language=interface_language,- interface_theme=interface_theme,- timezone=resolved_timezone,- last_login_ip=ip_address,- )-- session.add(account)- session.commit()- return account-- @staticmethod- def create_account_and_tenant(- email: str,- name: str,- interface_language: str,- password: str | None = None,- timezone: str | None = None,- ip_address: str | None = None,- check_normalized_email: bool = False,- *,- session: Session,- ) -> Account:- """Create an account and owner workspace."""- account = AccountService.create_account(- email=email,- name=name,- interface_language=interface_language,- password=password,- timezone=timezone,- ip_address=ip_address,- check_normalized_email=check_normalized_email,- session=session,- )-- try:- TenantService.create_owner_tenant_if_not_exist(account=account, session=session)- except Exception:- # Enterprise-only side-effect should run independently from personal workspace creation.- _try_join_enterprise_default_workspace(str(account.id))- raise-- _try_join_enterprise_default_workspace(str(account.id))-- return account-- @staticmethod- def update_account_email(account: Account, email: str, session: Session) -> Account:- """Update account email"""- account.email = email- account.normalized_email = normalize_email(email)- account_integrate = session.scalar(- select(AccountIntegrate).where(AccountIntegrate.account_id == account.id).limit(1)- )- if account_integrate:- session.delete(account_integrate)- session.add(account)- session.commit()- return account-- @staticmethod- def update_login_info(account: Account, session: Session, *, ip_address: str):- """Update last login time and ip"""- account.last_login_at = naive_utc_now()- account.last_login_ip = ip_address- session.add(account)- session.commit()-- @staticmethod- def login(account: Account, *, session: Session, ip_address: str | None = None) -> TokenPair:- if ip_address:- AccountService.update_login_info(account=account, session=session, ip_address=ip_address)-- if account.status == AccountStatus.PENDING:- account.status = AccountStatus.ACTIVE- session.commit()-- 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)-- AccountService._store_refresh_token(refresh_token, account_id)-- return TokenPair(access_token=access_token, refresh_token=refresh_token, csrf_token=csrf_token)-- @staticmethod- 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)-- @staticmethod- 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")-- @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)-- return TokenPair(access_token=new_access_token, refresh_token=new_refresh_token, csrf_token=csrf_token)-- @staticmethod- def load_logged_in_account(*, account_id: str, session: Session):- return AccountService.load_user(account_id, session)-- @classmethod- def send_reset_password_email(- cls,- account: Account | None = None,- email: str | None = None,- language: str = "en-US",- is_allow_register: bool = False,- ):- account_email = account.email if account else email- if account_email is None:- raise ValueError("Email must be provided.")-- if cls.reset_password_rate_limiter.is_rate_limited(account_email):- from controllers.console.auth.error import PasswordResetRateLimitExceededError-- raise PasswordResetRateLimitExceededError(int(cls.reset_password_rate_limiter.time_window / 60))-- code, token = cls.generate_reset_password_token(account_email, account)-- if account:- send_reset_password_mail_task.delay(- language=language,- to=account_email,- code=code,- )- else:- send_reset_password_mail_task_when_account_not_exist.delay(- language=language,- to=account_email,- is_allow_register=is_allow_register,- )- cls.reset_password_rate_limiter.increment_rate_limit(account_email)- return token-- @classmethod- def send_change_email_email(- cls,- account: Account,- email: str | None = None,- old_email: str | None = None,- language: str = "en-US",- phase: str | None = None,- ):- account_email = email if email is not None else account.email- if not phase:- raise ValueError("phase must be provided.")- if phase not in (cls.CHANGE_EMAIL_PHASE_OLD, cls.CHANGE_EMAIL_PHASE_NEW):- raise ValueError("phase must be one of old_email or new_email.")- if old_email is None:- raise ValueError("old_email must be provided.")-- if cls.change_email_rate_limiter.is_rate_limited(account_email):- from controllers.console.auth.error import EmailChangeRateLimitExceededError-- raise EmailChangeRateLimitExceededError(int(cls.change_email_rate_limiter.time_window / 60))-- code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])- token_data: ChangeEmailTokenData- if phase == cls.CHANGE_EMAIL_PHASE_OLD:- token_data = ChangeEmailOldEmailToken(- account_id=account.id,- email=account_email,- old_email=old_email,- code=code,- )- else:- token_data = ChangeEmailNewEmailToken(- account_id=account.id,- email=account_email,- old_email=old_email,- code=code,- )- token = cls.generate_change_email_token(token_data, account)-- send_change_mail_task.delay(- language=language,- to=account_email,- code=code,- phase=phase,- )- cls.change_email_rate_limiter.increment_rate_limit(account_email)- return token-- @classmethod- def send_change_email_completed_notify_email(- cls,- account: Account | None = None,- email: str | None = None,- language: str = "en-US",- ):- account_email = account.email if account else email- if account_email is None:- raise ValueError("Email must be provided.")-- send_change_mail_completed_notification_task.delay(- language=language,- to=account_email,- )-- @classmethod- def send_owner_transfer_email(- cls,- account: Account | None = None,- email: str | None = None,- language: str = "en-US",- workspace_name: str | None = "",- ):- account_email = account.email if account else email- if account_email is None:- raise ValueError("Email must be provided.")-- if cls.owner_transfer_rate_limiter.is_rate_limited(account_email):- from controllers.console.auth.error import OwnerTransferRateLimitExceededError-- raise OwnerTransferRateLimitExceededError(int(cls.owner_transfer_rate_limiter.time_window / 60))-- code, token = cls.generate_owner_transfer_token(account_email, account)- workspace_name = workspace_name or ""-- send_owner_transfer_confirm_task.delay(- language=language,- to=account_email,- code=code,- workspace=workspace_name,- )- cls.owner_transfer_rate_limiter.increment_rate_limit(account_email)- return token-- @classmethod- def send_old_owner_transfer_notify_email(- cls,- account: Account | None = None,- email: str | None = None,- language: str = "en-US",- workspace_name: str | None = "",- new_owner_email: str = "",- ):- account_email = account.email if account else email- if account_email is None:- raise ValueError("Email must be provided.")- workspace_name = workspace_name or ""-- send_old_owner_transfer_notify_email_task.delay(- language=language,- to=account_email,- workspace=workspace_name,- new_owner_email=new_owner_email,- )-- @classmethod- def send_new_owner_transfer_notify_email(- cls,- account: Account | None = None,- email: str | None = None,- language: str = "en-US",- workspace_name: str | None = "",- ):- account_email = account.email if account else email- if account_email is None:- raise ValueError("Email must be provided.")- workspace_name = workspace_name or ""-- send_new_owner_transfer_notify_email_task.delay(- language=language,- to=account_email,- workspace=workspace_name,- )-- @classmethod- def generate_reset_password_token(- cls,- email: str,- account: Account | None = None,- code: str | None = None,- additional_data: dict[str, Any] = {},- ):- if not code:- code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])- additional_data["code"] = code- token = TokenManager.generate_token(- account_id=account.id if account else None,- email=email,- token_type="reset_password",- additional_data=additional_data,- )- return code, token-- @classmethod- def generate_change_email_token(- cls,- token_data: ChangeEmailTokenData,- account: Account,- ) -> str:- token = TokenManager.generate_token(- account_id=account.id,- email=token_data.email,- token_type="change_email",- additional_data=token_data.to_token_manager_payload(),- )- return token-- @classmethod- def generate_owner_transfer_token(- cls,- email: str,- account: Account | None = None,- code: str | None = None,- additional_data: dict[str, Any] = {},- ):- if not code:- code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])- additional_data["code"] = code- token = TokenManager.generate_token(- account_id=account.id if account else None,- email=email,- token_type="owner_transfer",- additional_data=additional_data,- )- return code, token-- @classmethod- def revoke_reset_password_token(cls, token: str):- TokenManager.revoke_token(token, "reset_password")-- @classmethod- def revoke_change_email_token(cls, token: str):- TokenManager.revoke_token(token, "change_email")-- @classmethod- def revoke_owner_transfer_token(cls, token: str):- TokenManager.revoke_token(token, "owner_transfer")-- @classmethod- def get_reset_password_data(cls, token: str) -> dict[str, Any] | None:- return TokenManager.get_token_data(token, "reset_password")-- @classmethod- def get_change_email_data(cls, token: str) -> ChangeEmailTokenData | None:- token_data = TokenManager.get_token_data(token, "change_email")- if token_data is None:- return None- try:- return _change_email_token_adapter.validate_python(token_data)- except ValidationError:- logger.warning("change_email token %s has invalid payload", token, exc_info=True)- return None-- @classmethod- def get_owner_transfer_data(cls, token: str) -> dict[str, Any] | None:- return TokenManager.get_token_data(token, "owner_transfer")-- @staticmethod- def get_account_by_email_with_case_fallback(email: str, *, session: Session) -> Account | None:- """- Retrieve an account by email, matching case-insensitively.-- SSO-provisioned accounts keep the identity provider's original casing, while other entry- points (invites, registration, login) normalize input to lowercase before looking up an- account. An exact match is tried first since it uses the plain email index; the fallback- compares normalized_email so either direction of case mismatch still resolves to the same- account.- """- account = session.execute(select(Account).where(Account.email == email)).scalar_one_or_none()- if account:- return account-- return session.execute(- select(Account)- .where(Account.normalized_email == normalize_email(email))- .order_by(Account.created_at)- .limit(1)- ).scalar_one_or_none()-- @staticmethod- @redis_fallback(default_return=None)- def add_login_error_rate_limit(email: str):- key = f"login_error_rate_limit:{email}"- count = redis_client.get(key)- if count is None:- count = 0- count = int(count) + 1- redis_client.setex(key, dify_config.LOGIN_LOCKOUT_DURATION, count)-- @staticmethod- @redis_fallback(default_return=False)- def is_login_error_rate_limit(email: str) -> bool:- key = f"login_error_rate_limit:{email}"- count = redis_client.get(key)- if count is None:- return False-- count = int(count)- if count > AccountService.LOGIN_MAX_ERROR_LIMITS:- return True- return False-- @staticmethod- @redis_fallback(default_return=None)- def reset_login_error_rate_limit(email: str):- key = f"login_error_rate_limit:{email}"- redis_client.delete(key)-- @staticmethod- @redis_fallback(default_return=None)- def add_forgot_password_error_rate_limit(email: str):- key = f"{FORGOT_PASSWORD_VERIFICATION_KEY_PREFIX}:{email}"- count = redis_client.get(key)- if count is None:- count = 0- count = int(count) + 1- redis_client.setex(key, dify_config.FORGOT_PASSWORD_LOCKOUT_DURATION, count)-- @staticmethod- @redis_fallback(default_return=False)- def is_forgot_password_error_rate_limit(email: str) -> bool:- key = f"{FORGOT_PASSWORD_VERIFICATION_KEY_PREFIX}:{email}"- count = redis_client.get(key)- if count is None:- return False-- count = int(count)- if count > FORGOT_PASSWORD_VERIFICATION_FAILURE_LIMIT:- return True- return False-- @staticmethod- @redis_fallback(default_return=None)- def reset_forgot_password_error_rate_limit(email: str):- key = f"{FORGOT_PASSWORD_VERIFICATION_KEY_PREFIX}:{email}"- redis_client.delete(key)-- @staticmethod- @redis_fallback(default_return=None)- def add_change_email_error_rate_limit(email: str):- key = f"change_email_error_rate_limit:{email}"- count = redis_client.get(key)- if count is None:- count = 0- count = int(count) + 1- redis_client.setex(key, dify_config.CHANGE_EMAIL_LOCKOUT_DURATION, count)-- @staticmethod- @redis_fallback(default_return=False)- def is_change_email_error_rate_limit(email: str) -> bool:- key = f"change_email_error_rate_limit:{email}"- count = redis_client.get(key)- if count is None:- return False- count = int(count)- if count > AccountService.CHANGE_EMAIL_MAX_ERROR_LIMITS:- return True- return False-- @staticmethod- @redis_fallback(default_return=None)- def reset_change_email_error_rate_limit(email: str):- key = f"change_email_error_rate_limit:{email}"- redis_client.delete(key)-- @staticmethod- @redis_fallback(default_return=None)- def add_owner_transfer_error_rate_limit(email: str):- key = f"owner_transfer_error_rate_limit:{email}"- count = redis_client.get(key)- if count is None:- count = 0- count = int(count) + 1- redis_client.setex(key, dify_config.OWNER_TRANSFER_LOCKOUT_DURATION, count)-- @staticmethod- @redis_fallback(default_return=False)- def is_owner_transfer_error_rate_limit(email: str) -> bool:- key = f"owner_transfer_error_rate_limit:{email}"- count = redis_client.get(key)- if count is None:- return False- count = int(count)- if count > AccountService.OWNER_TRANSFER_MAX_ERROR_LIMITS:- return True- return False-- @staticmethod- @redis_fallback(default_return=None)- def reset_owner_transfer_error_rate_limit(email: str):- key = f"owner_transfer_error_rate_limit:{email}"- redis_client.delete(key)-- @staticmethod- @redis_fallback(default_return=False)- def is_email_send_ip_limit(ip_address: str):- 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}"-- # check ip is frozen- if redis_client.get(freeze_key):- return True-- # check current minute count- current_minute_count = redis_client.get(minute_key)- if current_minute_count is None:- current_minute_count = 0- current_minute_count = int(current_minute_count)-- # check current hour count- if current_minute_count > dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE:- hour_limit_count = redis_client.get(hour_limit_key)- if hour_limit_count is None:- hour_limit_count = 0- hour_limit_count = int(hour_limit_count)-- if hour_limit_count >= 1:- redis_client.setex(freeze_key, 60 * 60, 1)- return True-- # First strike claims a 10-minute window atomically; a concurrent- # over-limit request that loses the claim is the second strike and- # freezes the IP for an hour.- if not redis_client.set(hour_limit_key, 1, ex=60 * 10, nx=True):- redis_client.setex(freeze_key, 60 * 60, 1)-- return True-- redis_client.setex(minute_key, 60, current_minute_count + 1)- redis_client.expire(minute_key, 60)-- return False-- @staticmethod- def check_email_unique(email: str, *, session: Session) -> bool:- return session.scalar(select(Account).where(Account.email == email).limit(1)) is None---class TenantService:- @staticmethod- def create_tenant(- name: str,- is_setup: bool | None = False,- is_from_dashboard: bool | None = False,- *,- session: Session,- ) -> Tenant:- """Create tenant"""- if not SystemFeatureService.is_workspace_creation_allowed() and not is_setup and not is_from_dashboard:- from controllers.console.error import NotAllowedCreateWorkspace-- raise NotAllowedCreateWorkspace()- tenant = Tenant(name=name)-- session.add(tenant)- session.commit()-- for category in TenantPluginAutoUpgradeCategory:- plugin_upgrade_strategy = 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(plugin_upgrade_strategy)- session.commit()-- tenant.encrypt_public_key = generate_key_pair(tenant.id)- session.commit()-- from services.credit_pool_service import CreditPoolService-- CreditPoolService.create_default_pool(tenant.id, session=session)-- return tenant-- @staticmethod- def create_owner_tenant_if_not_exist(- account: Account, name: str | None = None, is_setup: bool | None = False, *, session: Session- ):- """Create an owner workspace only when the account has no membership."""- available_ta = session.scalar(- select(TenantAccountJoin)- .where(TenantAccountJoin.account_id == account.id)- .order_by(TenantAccountJoin.id.asc())- .limit(1)- )-- if available_ta:- return-- TenantService.create_owner_tenant(account, name=name, is_setup=is_setup, session=session)-- @staticmethod- def create_owner_tenant(- account: Account,- name: str | None = None,- is_setup: bool | None = False,- is_from_dashboard: bool | None = False,- *,- session: Session,- ) -> Tenant:- """Create an owner workspace and bind its owner RBAC role when enabled.-- This is the single write path for a newly created workspace with an- owner. It persists the legacy membership before creating the matching- RBAC role binding, then makes the workspace current for the account.- """- if not SystemFeatureService.is_workspace_creation_allowed() and not is_setup and not is_from_dashboard:- raise WorkSpaceNotAllowedCreateError()-- workspaces = SystemFeatureService.get_license().workspaces- if not workspaces.is_available():- raise WorkspacesLimitExceededError()-- if name:- tenant = TenantService.create_tenant(- name=name,- is_setup=is_setup,- is_from_dashboard=is_from_dashboard,- session=session,- )- else:- tenant = TenantService.create_tenant(- name=f"{account.name}'s Workspace",- is_setup=is_setup,- is_from_dashboard=is_from_dashboard,- session=session,- )- TenantService.create_tenant_member(tenant, account, session, role="owner")- if dify_config.RBAC_ENABLED:- owner_role_id = AccountService._resolve_legacy_role_id(str(tenant.id), account.id, TenantAccountRole.OWNER)- RBACService.MemberRoles.replace(- tenant_id=str(tenant.id),- account_id=account.id,- member_account_id=account.id,- role_ids=[owner_role_id],- session=session,- )- account.set_current_tenant_with_session(tenant, session=session)- session.commit()- tenant_was_created.send(tenant)- return tenant-- @staticmethod- def create_tenant_member(- tenant: Tenant,- account: Account,- session: Session,- role: str = "normal",- *,- operator_account_id: str | None = None,- ) -> TenantAccountJoin:- """Create tenant member"""- if role == TenantAccountRole.OWNER:- if TenantService.has_roles(tenant, [TenantAccountRole.OWNER], session=session):- logger.error("Tenant %s has already an owner.", tenant.id)- raise Exception("Tenant already has an owner.")-- ta = session.scalar(- select(TenantAccountJoin)- .where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == account.id)- .limit(1)- )- if ta:- ta.role = TenantAccountRole(role)- membership_created = False- else:- ta = TenantAccountJoin(tenant_id=tenant.id, account_id=account.id, role=TenantAccountRole(role))- session.add(ta)- membership_created = True-- session.commit()- if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:- BillingService.clean_billing_info_cache(tenant.id)- if (- membership_created- and dify_config.RBAC_ENABLED- and TenantAccountRole(role) != TenantAccountRole.OWNER- and account.status != AccountStatus.PENDING- ):- 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(tenant.id),- str(account.id),- operator_account_id=operator_account_id,- )- return ta-- @staticmethod- def join_enterprise_workspace_member(- *,- workspace_id: str,- account_id: str,- email: str,- role: TenantAccountRole,- operator_account_id: str | None,- session: Session | None = None,- ) -> TenantAccountJoin:- session = session or db.session()- tenant = session.scalar(- select(Tenant).where(- Tenant.id == workspace_id,- Tenant.status == TenantStatus.NORMAL,- )- )- if tenant is None:- raise EnterpriseWorkspaceMemberWorkspaceNotFoundError-- account = session.scalar(- select(Account).where(- Account.id == account_id,- Account.email == email,- )- )- if account is None:- raise EnterpriseWorkspaceMemberAccountNotFoundError-- return TenantService.create_tenant_member(- tenant,- account,- session=session,- role=role.value,- operator_account_id=operator_account_id,- )-- @staticmethod- def get_join_tenants(account: Account, *, session: Session) -> list[Tenant]:- """Get account join tenants"""- return list(- session.scalars(- select(Tenant)- .join(TenantAccountJoin, Tenant.id == TenantAccountJoin.tenant_id)- .where(TenantAccountJoin.account_id == account.id, Tenant.status == TenantStatus.NORMAL)- ).all()- )-- @staticmethod- def get_workspaces_for_account(account_id: str, *, session: Session) -> list[Row[tuple[Tenant, TenantAccountJoin]]]:- """``(Tenant, TenantAccountJoin)`` rows for every workspace the- account belongs to, ordered by ``Tenant.created_at`` ASC — the- canonical ordering for ``/openapi/v1/workspaces``. Rows keep the- tenant first so callers can serialize the workspace directly.- """- return list(- session.execute(- select(Tenant, TenantAccountJoin)- .join(TenantAccountJoin, TenantAccountJoin.tenant_id == Tenant.id)- .where(TenantAccountJoin.account_id == account_id)- .order_by(Tenant.created_at.asc())- ).all()- )-- @staticmethod- def account_belongs_to_tenant(account_id: uuid.UUID | str | None, tenant_id: str, *, session: Session) -> bool:- """Existence check for ``TenantAccountJoin(account_id, tenant_id)``.- Membership without the role: where the openapi auth layer needs the role- itself it reads ``Context.workspace_role`` instead.-- ``None``/empty ``account_id`` short-circuits to ``False`` so SSO- bearers (no account) and missing identity collapse cleanly.- """- if not account_id:- return False- row = session.execute(- select(TenantAccountJoin.id).where(- TenantAccountJoin.tenant_id == tenant_id,- TenantAccountJoin.account_id == account_id,- )- ).scalar_one_or_none()- return row is not None-- @staticmethod- def get_account_role_in_tenant(- account_id: uuid.UUID | str | None, tenant_id: str, *, session: Session- ) -> TenantAccountRole | None:- """Return the caller's role in ``tenant_id``, or ``None`` if not a member.-- Backs the openapi auth layer's ``Context.workspace_role``: ``None`` is- treated as non-member (mapped to 404 — no cross-tenant ID leak) and an- out-of-set role to 403.-- ``None``/empty ``account_id`` short-circuits to ``None`` so SSO- bearers (no account) collapse to the non-member path. Mirrors the- session-injection style of :meth:`account_belongs_to_tenant` rather- than :meth:`get_user_role`, which loads full ``Account``/``Tenant``- objects against the Flask-scoped session.- """- if not account_id:- return None-- role = session.execute(- select(TenantAccountJoin.role).where(- TenantAccountJoin.tenant_id == tenant_id,- TenantAccountJoin.account_id == account_id,- )- ).scalar_one_or_none()- return TenantAccountRole(role) if role is not None else None-- @staticmethod- def get_tenant_by_id(tenant_id: str, *, session: Session) -> Tenant | None:- """Plain ``session.get(Tenant, tenant_id)`` — no status filter.- Callers map ``status == ARCHIVE`` to their own error code (the- openapi auth pipeline raises 403 ``workspace unavailable``).- """- return session.get(Tenant, tenant_id)-- @staticmethod- def get_tenants_by_ids(tenant_ids: list[str], *, session: Session) -> list[Tenant]:- """Bulk ``Tenant`` fetch by primary-key list. Order is unspecified- — callers index by ``tenant.id`` (e.g. for cross-tenant denorm- in ``/openapi/v1/permitted-external-apps``).-- Empty input short-circuits to ``[]`` to avoid emitting an- ``IN ()`` SQL fragment.- """- if not tenant_ids:- return []- return list(session.execute(select(Tenant).where(Tenant.id.in_(tenant_ids))).scalars().all())-- @staticmethod- def get_tenant_name(tenant_id: str, *, session: Session) -> str | None:- """Single-column tenant name read. Used by openapi list endpoints- to denormalize ``workspace_name`` onto each row without dragging- the full ``Tenant`` ORM entity through.- """- return session.execute(select(Tenant.name).where(Tenant.id == tenant_id)).scalar_one_or_none()-- @staticmethod- def find_workspace_for_account(- account_id: str, workspace_id: str, *, session: Session- ) -> Row[tuple[Tenant, TenantAccountJoin]] | None:- """Single ``(Tenant, TenantAccountJoin)`` row scoped to the- account's membership in ``workspace_id``. ``None`` on non-member- — the caller maps that to 404 (not 403) so workspace IDs don't- leak across tenants via response codes.- """- return session.execute(- select(Tenant, TenantAccountJoin)- .join(TenantAccountJoin, TenantAccountJoin.tenant_id == Tenant.id)- .where(- Tenant.id == workspace_id,- TenantAccountJoin.account_id == account_id,- )- ).first()-- @staticmethod- def switch_tenant(account: Account, tenant_id: str | None = None, *, session: Session):- """Switch the current workspace for the account"""-- # Ensure tenant_id is provided- if tenant_id is None:- raise ValueError("Tenant ID must be provided.")-- tenant_account_join = session.scalar(- select(TenantAccountJoin)- .join(Tenant, TenantAccountJoin.tenant_id == Tenant.id)- .where(- TenantAccountJoin.account_id == account.id,- TenantAccountJoin.tenant_id == tenant_id,- Tenant.status == TenantStatus.NORMAL,- )- .limit(1)- )-- if not tenant_account_join:- raise AccountNotLinkTenantError("Tenant not found or account is not a member of the tenant.")- else:- session.execute(- update(TenantAccountJoin)- .where(TenantAccountJoin.account_id == account.id, TenantAccountJoin.tenant_id != tenant_id)- .values(current=False)- )- tenant_account_join.current = True- tenant_account_join.last_opened_at = naive_utc_now()- # Set the current tenant for the account- account.set_tenant_id_with_session(tenant_account_join.tenant_id, session=session)- session.commit()-- @staticmethod- def get_tenant_members(tenant: Tenant, *, session: Session) -> list[Account]:- """Get tenant members"""- stmt = (- select(Account, TenantAccountJoin.role)- .select_from(Account)- .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)- .where(TenantAccountJoin.tenant_id == tenant.id)- )-- # Initialize an empty list to store the updated accounts- updated_accounts = []-- for account, role in session.execute(stmt):- account.role = role- updated_accounts.append(account)-- return updated_accounts-- @staticmethod- def iter_member_account_id_batches(tenant_id: str, batch_size: int, *, session: Session) -> Iterator[list[str]]:- """Yield workspace member account ids in bounded, ordered batches."""- offset = 0- while True:- stmt = (- select(TenantAccountJoin.account_id)- .where(TenantAccountJoin.tenant_id == tenant_id)- .order_by(TenantAccountJoin.id)- .offset(offset)- .limit(batch_size)- )- account_ids = list(session.scalars(stmt).all())- if not account_ids:- return-- yield account_ids- offset += batch_size-- @staticmethod- def get_dataset_operator_members(tenant: Tenant, *, session: Session) -> list[Account]:- """Get dataset admin members"""- stmt = (- select(Account, TenantAccountJoin.role)- .select_from(Account)- .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)- .where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.role == "dataset_operator")- )-- # Initialize an empty list to store the updated accounts- updated_accounts = []-- for account, role in session.execute(stmt):- account.role = role- updated_accounts.append(account)-- return updated_accounts-- @staticmethod- def has_roles(tenant: Tenant, roles: list[TenantAccountRole], *, session: Session) -> bool:- """Check if user has any of the given roles for a tenant"""- if not all(isinstance(role, TenantAccountRole) for role in roles):- raise ValueError("all roles must be TenantAccountRole")-- return (- session.scalar(- select(TenantAccountJoin)- .where(- TenantAccountJoin.tenant_id == tenant.id,- TenantAccountJoin.role.in_([role.value for role in roles]),- )- .limit(1)- )- is not None- )-- @staticmethod- def get_user_role(account: Account, tenant: Tenant, *, session: Session) -> TenantAccountRole | None:- """Get the role of the current account for a given tenant"""- join = session.scalar(- select(TenantAccountJoin)- .where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == account.id)- .limit(1)- )- return TenantAccountRole(join.role) if join else None-- @staticmethod- def check_member_permission(- tenant: Tenant, operator: Account, member: Account | None, action: str, *, session: Session- ):- """Check member permission"""- if action not in {"add", "remove", "update"}:- raise InvalidActionError("Invalid action.")-- if member:- if operator.id == member.id:- raise CannotOperateSelfError("Cannot operate self.")-- if dify_config.RBAC_ENABLED:- workspace_permission_keys = AccountService.get_workspace_permission_keys(- str(tenant.id),- str(operator.id),- session=session,- )- required_permission_key = (- "workspace.member.manage" if action in {"add", "remove"} else "workspace.role.manage"- )- if required_permission_key not in workspace_permission_keys:- raise NoPermissionError(f"No permission to {action} member.")-- if (- action == "remove"- and member- and AccountService.is_rbac_workspace_owner(- str(tenant.id), str(operator.id), str(member.id), session=session- )- ):- raise NoPermissionError(f"No permission to {action} member.")- return-- perms = {- "add": [TenantAccountRole.OWNER, TenantAccountRole.ADMIN],- "remove": [TenantAccountRole.OWNER, TenantAccountRole.ADMIN],- "update": [TenantAccountRole.OWNER, TenantAccountRole.ADMIN],- }-- ta_operator = session.scalar(- select(TenantAccountJoin)- .where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == operator.id)- .limit(1)- )-- if not ta_operator or ta_operator.role not in perms[action]:- raise NoPermissionError(f"No permission to {action} member.")-- if action == "remove" and ta_operator.role == TenantAccountRole.ADMIN and member:- ta_member = session.scalar(- select(TenantAccountJoin)- .where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == member.id)- .limit(1)- )- if ta_member and ta_member.role == TenantAccountRole.OWNER:- raise NoPermissionError(f"No permission to {action} member.")-- @staticmethod- def remove_member_from_tenant(tenant: Tenant, account: Account, operator: Account, *, session: Session):- """Remove member from tenant.-- Apps and datasets maintained by the removed member are reassigned to- the workspace owner without changing their immutable creator records.- If the removed member has ``AccountStatus.PENDING`` (invited but never- activated) and no remaining workspace memberships, the orphaned account- record is deleted as well.- """- if operator.id == account.id:- raise CannotOperateSelfError("Cannot operate self.")-- TenantService.check_member_permission(tenant, operator, account, "remove", session=session)-- ta = session.scalar(- select(TenantAccountJoin)- .where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == account.id)- .limit(1)- )- if not ta:- raise MemberNotInTenantError("Member not in tenant.")-- # Capture identifiers before any deletions; attribute access on the ORM- # object may fail after commit() expires the instance.- account_id = account.id- account_email = account.email-- owner_id: str | None- if dify_config.RBAC_ENABLED:- owner_id = AccountService.get_rbac_workspace_owner_account_id(- str(tenant.id), str(operator.id), session=session- )- else:- owner_id = session.scalar(- select(TenantAccountJoin.account_id)- .where(- TenantAccountJoin.tenant_id == tenant.id,- TenantAccountJoin.role == TenantAccountRole.OWNER,- )- .limit(1)- )- if owner_id is None:- raise ValueError(f"Workspace owner not found for tenant {tenant.id}.")-- session.execute(- update(App)- .where(- App.tenant_id == tenant.id,- App.maintainer == account_id,- )- .values(maintainer=owner_id)- )- session.execute(- update(Dataset)- .where(- Dataset.tenant_id == tenant.id,- Dataset.maintainer == account_id,- )- .values(maintainer=owner_id)- )- session.delete(ta)-- # Clean up orphaned pending accounts (invited but never activated)- should_delete_account = False- if account.status == AccountStatus.PENDING:- # autoflush flushes ta deletion before this query, so 0 means no remaining joins- remaining_joins = (- session.scalar(- select(func.count(TenantAccountJoin.id)).where(TenantAccountJoin.account_id == account_id)- )- or 0- )- if remaining_joins == 0:- session.delete(account)- should_delete_account = True-- session.commit()-- if should_delete_account:- logger.info(- "Deleted orphaned pending account: account_id=%s, email=%s",- account_id,- account_email,- )-- if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:- BillingService.clean_billing_info_cache(tenant.id)-- # Queue account deletion sync task for enterprise backend to reassign resources (enterprise only)- from services.enterprise.account_deletion_sync import sync_workspace_member_removal-- sync_success = sync_workspace_member_removal(- workspace_id=tenant.id, member_id=account_id, source="workspace_member_removed"- )- if not sync_success:- logger.warning(- "Enterprise workspace member removal sync failed: workspace_id=%s, member_id=%s",- tenant.id,- account_id,- )-- if dify_config.RBAC_ENABLED:- RBACService.MemberRoles.delete_rbac_bindings(tenant_id=tenant.id, account_id=account_id)-- @staticmethod- def update_member_role(tenant: Tenant, member: Account, new_role: str, operator: Account, *, session: Session):- """Update member role"""- TenantService.check_member_permission(tenant, operator, member, "update", session=session)- new_tenant_role = TenantAccountRole(new_role)-- target_member_join = session.scalar(- select(TenantAccountJoin)- .where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == member.id)- .limit(1)- )-- if not target_member_join:- raise MemberNotInTenantError("Member not in tenant.")-- operator_role = TenantService.get_user_role(operator, tenant, session=session)- target_role = TenantAccountRole(target_member_join.role)- if operator_role == TenantAccountRole.ADMIN and (TenantAccountRole.OWNER in {target_role, new_tenant_role}):- raise NoPermissionError("No permission to update member.")-- if target_member_join.role == new_role:- raise RoleAlreadyAssignedError("The provided role is already assigned to the member.")-- if new_role == "owner":- if dify_config.RBAC_ENABLED:- old_owner_id = AccountService.get_rbac_workspace_owner_account_id(- str(tenant.id), operator.id, session=session- )- owner_role_id = AccountService._resolve_legacy_role_id(- tenant_id=str(tenant.id),- account_id=operator.id,- role=TenantAccountRole.OWNER,- )- no_access_role_id = AccountService._resolve_role_id_by_tag(- tenant_id=str(tenant.id),- account_id=operator.id,- tag="no_access",- )- current_roles = RBACService.MemberRoles.get(- str(tenant.id), operator.id, old_owner_id, session=session- ).roles- remaining_role_ids = [str(r.id) for r in current_roles if str(r.id) != owner_role_id]- RBACService.MemberRoles.replace(- tenant_id=str(tenant.id),- account_id=operator.id,- member_account_id=old_owner_id,- role_ids=remaining_role_ids or [no_access_role_id],- session=session,- )-- current_owner_join = session.scalar(- select(TenantAccountJoin)- .where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.role == "owner")- .limit(1)- )- if current_owner_join:- current_owner_join.role = TenantAccountRole.NORMAL-- # Update the role of the target member- if dify_config.RBAC_ENABLED:- resolved_role_id = AccountService._resolve_legacy_role_id(- tenant_id=str(tenant.id),- account_id=operator.id,- role=TenantAccountRole.OWNER,- )- RBACService.MemberRoles.replace(- tenant_id=str(tenant.id),- account_id=operator.id,- member_account_id=member.id,- role_ids=[resolved_role_id],- session=session,- )- if new_tenant_role == TenantAccountRole.OWNER:- target_member_join.role = new_tenant_role- else:- target_member_join.role = new_tenant_role- session.commit()-- @staticmethod- def is_owner(account: Account, tenant: Tenant, *, session: Session) -> bool:- return TenantService.get_user_role(account, tenant, session=session) == TenantAccountRole.OWNER-- @staticmethod- def is_member(account: Account, tenant: Tenant, *, session: Session) -> bool:- """Check if the account is a member of the tenant"""- return TenantService.get_user_role(account, tenant, session=session) is not None---class RegisterService:- @classmethod- def _get_invitation_token_key(cls, token: str) -> str:- return f"member_invite:token:{token}"-- @classmethod- def setup(- cls,- email: str,- name: str,- password: str,- ip_address: str,- language: str | None,- *,- session: Session,- ):- """- Setup dify-- :param email: email- :param name: username- :param password: password- :param ip_address: ip address- :param language: language- """- try:- account = AccountService.create_account(- email=email,- name=name,- interface_language=get_valid_language(language),- password=password,- is_setup=True,- ip_address=ip_address,- session=session,- )-- account.initialized_at = naive_utc_now()-- TenantService.create_owner_tenant_if_not_exist(account=account, is_setup=True, session=session)-- dify_setup = DifySetup(version=dify_config.project.version, instance_id=str(uuid.uuid4()))- session.add(dify_setup)- session.commit()- except Exception as e:- session.execute(delete(DifySetup))- session.execute(delete(TenantAccountJoin))- session.execute(delete(Account))- session.execute(delete(Tenant))- session.commit()-- logger.exception("Setup account failed, email: %s, name: %s", email, name)- raise ValueError(f"Setup failed: {e}")-- try:- CommunityTelemetryService.report_install(session=session)- except Exception:- logger.debug("Failed to report install telemetry", exc_info=True)-- @classmethod- def register(- cls,- email: str,- name: str,- password: str | None = None,- language: str | None = None,- status: AccountStatus | None = None,- is_setup: bool | None = False,- create_workspace_required: bool | None = True,- timezone: str | None = None,- ip_address: str | None = None,- check_normalized_email: bool = True,- *,- session: Session,- ) -> Account:- """Register account"""- session.begin_nested()- try:- interface_language = get_valid_language(language)- account = AccountService.create_account(- email=email,- name=name,- interface_language=interface_language,- password=password,- is_setup=is_setup,- timezone=timezone,- ip_address=ip_address,- check_normalized_email=check_normalized_email,- session=session,- )- account.status = status or AccountStatus.ACTIVE- account.initialized_at = naive_utc_now()-- if (- SystemFeatureService.is_workspace_creation_allowed()- and create_workspace_required- and SystemFeatureService.get_license().workspaces.is_available()- ):- try:- TenantService.create_owner_tenant(account, session=session)- except Exception:- _try_join_enterprise_default_workspace(str(account.id))- raise-- session.commit()-- _try_join_enterprise_default_workspace(str(account.id))- except WorkSpaceNotAllowedCreateError:- session.rollback()- logger.exception("Register failed")- raise AccountRegisterError("Workspace is not allowed to create.")- except SeatsLimitExceededError:- session.rollback()- logger.exception("Register failed")- raise- except AccountRegisterError as are:- session.rollback()- logger.exception("Register failed")- raise are- except Exception as e:- session.rollback()- logger.exception("Register failed")- raise AccountRegisterError(f"Registration failed: {e}") from e-- return account-- @classmethod- def invite_new_member(- cls,- tenant: Tenant,- email: str,- language: str | None,- role: str = "normal",- inviter: Account | None = None,- *,- session: Session,- ) -> str:- if not inviter:- raise ValueError("Inviter is required")-- normalized_email = email.lower()- tenant_join_role = TenantAccountRole.NORMAL.value if dify_config.RBAC_ENABLED else role-- """Invite new member"""- # Check workspace permission for member invitations- from libs.workspace_permission import check_workspace_member_invite_permission-- check_workspace_member_invite_permission(tenant.id)-- account = AccountService.get_account_by_email_with_case_fallback(email, session=session)-- requires_setup = False- if not account:- TenantService.check_member_permission(tenant, inviter, None, "add", session=session)- name = normalized_email.split("@")[0]-- account = cls.register(- email=normalized_email,- name=name,- language=language,- status=AccountStatus.PENDING,- is_setup=True,- check_normalized_email=True,- session=session,- )- TenantService.create_tenant_member(- tenant,- account,- session,- tenant_join_role,- operator_account_id=inviter.id,- )- TenantService.switch_tenant(account, tenant.id, session=session)- requires_setup = True- else:- TenantService.check_member_permission(tenant, inviter, account, "add", session=session)- ta = session.scalar(- select(TenantAccountJoin)- .where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == account.id)- .limit(1)- )- requires_setup = account.status == AccountStatus.PENDING-- if not ta and (account.status == AccountStatus.PENDING or dify_config.RBAC_ENABLED):- TenantService.create_tenant_member(- tenant,- account,- session,- tenant_join_role,- operator_account_id=inviter.id,- )-- # Support resend invitation email when the account is pending status- if account.status != AccountStatus.PENDING:- if dify_config.RBAC_ENABLED and not ta:- RBACService.MemberRoles.replace(- tenant_id=str(tenant.id),- account_id=inviter.id,- member_account_id=account.id,- role_ids=[role],- session=session,- )- if ta or dify_config.RBAC_ENABLED:- raise AccountAlreadyInTenantError("Account already in tenant.")-- # Assign RBAC role if RBAC is enabled- if dify_config.RBAC_ENABLED:- RBACService.MemberRoles.replace(- tenant_id=str(tenant.id),- account_id=inviter.id,- member_account_id=account.id,- role_ids=[role],- session=session,- )-- token = cls.generate_invite_token(tenant, account, role, requires_setup=requires_setup)- language = account.interface_language or "en-US"-- # send email- send_invite_member_mail_task.delay(- language=language,- to=account.email,- token=token,- inviter_name=inviter.name if inviter else "Dify",- workspace_name=tenant.name,- )-- return token-- @classmethod- def generate_invite_token(- cls, tenant: Tenant, account: Account, role: str = "normal", *, requires_setup: bool = False- ) -> str:- token = str(uuid.uuid4())- invitation_data = {- "account_id": account.id,- "email": account.email,- "workspace_id": tenant.id,- "role": str(role),- "requires_setup": requires_setup,- }- expiry_hours = dify_config.INVITE_EXPIRY_HOURS- redis_client.setex(cls._get_invitation_token_key(token), expiry_hours * 60 * 60, json.dumps(invitation_data))- return token-- @classmethod- def revoke_token(cls, workspace_id: str | None, email: str | None, token: str):- if workspace_id and email:- email_hash = sha256(email.encode()).hexdigest()- cache_key = f"member_invite_token:{workspace_id}, {email_hash}:{token}"- redis_client.delete(cache_key)- else:- redis_client.delete(cls._get_invitation_token_key(token))-- @classmethod- def get_invitation_if_token_valid(- cls, workspace_id: str | None, email: str | None, token: str, *, session: Session- ) -> InvitationDetailDict | None:- invitation_data = cls.get_invitation_by_token(token, workspace_id, email)- if not invitation_data:- return None-- tenant = session.scalar(- select(Tenant).where(Tenant.id == invitation_data["workspace_id"], Tenant.status == "normal").limit(1)- )-- if not tenant:- return None-- account = session.scalar(select(Account).where(Account.email == invitation_data["email"]).limit(1))- if not account:- return None-- if invitation_data["account_id"] != str(account.id):- return None-- return {- "account": account,- "data": invitation_data,- "tenant": tenant,- }-- @classmethod- def get_invitation_by_token(- cls, token: str, workspace_id: str | None = None, email: str | None = None- ) -> InvitationData | None:- if workspace_id is not None and email is not None:- email_hash = sha256(email.encode()).hexdigest()- cache_key = f"member_invite_token:{workspace_id}, {email_hash}:{token}"- account_id = redis_client.get(cache_key)-- if not account_id:- return None-- return {- "account_id": account_id.decode("utf-8"),- "email": email,- "workspace_id": workspace_id,- }- else:- data = redis_client.get(cls._get_invitation_token_key(token))- if not data:- return None-- invitation = _invitation_adapter.validate_json(data)- return invitation-- @classmethod- def get_invitation_with_case_fallback(- cls, workspace_id: str | None, email: str | None, token: str, *, session: Session- ) -> InvitationDetailDict | None:- invitation = cls.get_invitation_if_token_valid(workspace_id, email, token, session=session)- if invitation or not email or email == email.lower():- return invitation- normalized_email = email.lower()- return cls.get_invitation_if_token_valid(workspace_id, normalized_email, token, session=session)---def _generate_refresh_token(length: int = 64):- token = secrets.token_hex(length)- return tokendiff --git a/api/services/annotation_service.py b/api/services/annotation_service.pyindex 479efb83bfb..52c3eddc153 100644--- a/api/services/annotation_service.py+++ b/api/services/annotation_service.py@@ -14,6 +14,7 @@ from extensions.ext_redis import redis_clientfrom libs.datetime_utils import naive_utc_nowfrom libs.login import current_account_with_tenantfrom libs.pagination import paginate_query+from models.account import Accountfrom models.dataset import DatasetCollectionBindingfrom models.model import App, AppAnnotationHitHistory, AppAnnotationSetting, Message, MessageAnnotationfrom services.app_ref_service import AnnotationRef, AppRef@@ -597,6 +598,18 @@ class AppAnnotationService:return Nonereturn annotation+ @classmethod+ def get_annotation_reply_by_id(+ cls, annotation_id: str, session: Session+ ) -> tuple[MessageAnnotation, str | None] | None:+ """Read a reply and its author together, retaining annotations whose account was deleted."""+ row = session.execute(+ select(MessageAnnotation, Account.name)+ .outerjoin(Account, Account.id == MessageAnnotation.account_id)+ .where(MessageAnnotation.id == annotation_id)+ ).one_or_none()+ return (row[0], row[1]) if row is not None else None+@classmethoddef add_annotation_history(cls,diff --git a/api/services/app/console_gateway.py b/api/services/app/console_gateway.pyindex 64a08fb2bcf..519d9a7d682 100644--- a/api/services/app/console_gateway.py+++ b/api/services/app/console_gateway.py@@ -61,7 +61,7 @@ from services.entities.dsl_entities import (Import,ImportStatus,)-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.feature_service import FeatureServicefrom services.recommended_app_package_service import RecommendedAppPackageServicefrom services.system_feature_service import SystemFeatureServicediff --git a/api/services/app_dsl_service.py b/api/services/app_dsl_service.pyindex 6ef368bc206..dde4462d456 100644--- a/api/services/app_dsl_service.py+++ b/api/services/app_dsl_service.py@@ -71,8 +71,8 @@ from services.entities.dsl_entities import (make_app_dsl,)from services.entities.site_dsl import SiteDsl, apply_site_dsl-from services.errors.account import NoPermissionErrorfrom services.errors.app import WorkflowNotFoundError+from services.errors.base import NoPermissionErrorfrom services.feature_service import FeatureServicefrom services.icon_configuration import (DEFAULT_ICON,diff --git a/api/services/credit_pool_service.py b/api/services/credit_pool_service.pyindex bc4d31b58a0..577d16bdd47 100644--- a/api/services/credit_pool_service.py+++ b/api/services/credit_pool_service.py@@ -192,19 +192,6 @@ class CreditPoolService:.with_for_update())- @classmethod- def create_default_pool(cls, tenant_id: str, session: Session) -> TenantCreditPool:- """create default credit pool for new tenant"""- credit_pool = TenantCreditPool(- tenant_id=tenant_id,- quota_limit=dify_config.HOSTED_POOL_CREDITS,- quota_used=0,- pool_type=ProviderQuotaType.TRIAL,- )- session.add(credit_pool)- session.commit()- return credit_pool-@classmethoddef get_pool(cls,diff --git a/api/services/entities/account_login_entities.py b/api/services/entities/account_login_entities.pyindex 140a42522d2..5700b9c8922 100644--- a/api/services/entities/account_login_entities.py+++ b/api/services/entities/account_login_entities.py@@ -4,7 +4,7 @@ from dataclasses import dataclassfrom datetime import datetimefrom enum import StrEnum-from services.entities.account_entities import AccountPasswordDigest+from services.entities.account_entities import AccountPasswordDigest, AccountSessionTokensclass EmailCodeChallengeStatus(StrEnum):@@ -54,13 +54,6 @@ class AccountSessionPreparation: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@@ -90,5 +83,5 @@ class EmailCodeLoginCommand:@dataclass(frozen=True, slots=True)class PasswordLoginResult:- token_pair: AuthTokenPair | None+ tokens: AccountSessionTokens | Noneworkspace_found: booldiff --git a/api/services/errors/__init__.py b/api/services/errors/__init__.pyindex 15f004463d3..097e007ad68 100644--- a/api/services/errors/__init__.py+++ b/api/services/errors/__init__.py@@ -1,5 +1,4 @@from . import (- account,app,app_model_config,audio,@@ -14,7 +13,6 @@ from . import ()__all__ = [- "account","app","app_model_config","audio",diff --git a/api/services/errors/account.py b/api/services/errors/account.pydeleted file mode 100644index aa9084efb30..00000000000--- a/api/services/errors/account.py+++ /dev/null@@ -1,70 +0,0 @@-from services.errors.base import BaseServiceError---class AccountNotFoundError(BaseServiceError):- pass---class AccountRegisterError(BaseServiceError):- pass---class AccountEmailAlreadyInUseError(AccountRegisterError):- pass---class AccountNormalizedEmailAlreadyInUseError(AccountEmailAlreadyInUseError):- pass---class EmailDomainSuspendedError(AccountRegisterError):- def __init__(self, description: str = "This email domain has been suspended."):- super().__init__(description)---class AccountLoginError(BaseServiceError):- pass---class AccountPasswordError(BaseServiceError):- pass---class RefreshTokenNotFoundError(BaseServiceError):- pass---class AccountNotLinkTenantError(BaseServiceError):- pass---class TenantNotFoundError(BaseServiceError):- pass---class AccountAlreadyInTenantError(BaseServiceError):- pass---class SeatsLimitExceededError(BaseServiceError):- pass---class InvalidActionError(BaseServiceError):- pass---class CannotOperateSelfError(BaseServiceError):- pass---class NoPermissionError(BaseServiceError):- pass---class MemberNotInTenantError(BaseServiceError):- pass---class RoleAlreadyAssignedError(BaseServiceError):- passdiff --git a/api/services/errors/base.py b/api/services/errors/base.pyindex 12eb6f51d06..3f512454472 100644--- a/api/services/errors/base.py+++ b/api/services/errors/base.py@@ -1,3 +1,7 @@class BaseServiceError(ValueError):def __init__(self, description: str = ""):self.description = description+++class NoPermissionError(Exception):+ """The actor is not permitted to perform the requested operation."""diff --git a/api/services/errors/workspace.py b/api/services/errors/workspace.pyindex 18ff8b6eccd..2285500c0cf 100644--- a/api/services/errors/workspace.py+++ b/api/services/errors/workspace.py@@ -1,9 +1,95 @@-from services.errors.base import BaseServiceError+"""Framework-neutral failures owned by workspace application services."""-class WorkSpaceNotAllowedCreateError(BaseServiceError):+class WorkspaceApplicationError(Exception):+ """Base class for workspace use-case failures, mapped by transport adapters."""+++class AccountAlreadyInTenantError(WorkspaceApplicationError):+ pass+++class InvalidActionError(WorkspaceApplicationError):+ pass+++class CannotOperateSelfError(WorkspaceApplicationError):+ pass+++class MemberNotInTenantError(WorkspaceApplicationError):+ pass+++class RoleAlreadyAssignedError(WorkspaceApplicationError):+ pass+++class WorkSpaceNotAllowedCreateError(WorkspaceApplicationError):+ pass+++class WorkspacesLimitExceededError(WorkspaceApplicationError):+ pass+++class WorkspaceNotFoundError(WorkspaceApplicationError):+ pass+++class WorkspaceArchivedError(WorkspaceApplicationError):pass-class WorkspacesLimitExceededError(BaseServiceError):+class WorkspaceNotLinkedError(WorkspaceApplicationError):pass+++class WorkspaceOwnerNotFoundError(WorkspaceApplicationError):+ pass+++class WorkspaceAlreadyHasOwnerError(WorkspaceApplicationError):+ """An owner cannot join a workspace that already has one."""+++class InvalidWorkspaceMemberRoleError(WorkspaceApplicationError):+ pass+++class OwnerTransferSendIPLimitedError(WorkspaceApplicationError):+ """The caller IP exceeded the ownership-transfer email-send policy."""+++class OwnerTransferSendRateLimitError(WorkspaceApplicationError):+ """Too many ownership-transfer confirmation messages were requested."""++ def __init__(self, retry_after_minutes: int) -> None:+ super().__init__("Too many ownership-transfer confirmation messages")+ self.retry_after_minutes = retry_after_minutes+++class OwnerTransferVerificationLimitError(WorkspaceApplicationError):+ """Too many invalid ownership-transfer verification codes were submitted."""+++class InvalidOwnerTransferTokenError(WorkspaceApplicationError):+ """The ownership-transfer token is missing or invalid."""+++class InvalidOwnerTransferEmailError(WorkspaceApplicationError):+ """The ownership-transfer token belongs to another email address."""+++class InvalidOwnerTransferCodeError(WorkspaceApplicationError):+ """The verification code does not match the ownership-transfer token."""+++class WorkspaceInvitationQuotaError(WorkspaceApplicationError):+ def __init__(self, *, seats: bool = False) -> None:+ super().__init__("Workspace invitation quota exceeded")+ self.seats = seats+++class WorkspaceMemberLicenseQuotaError(WorkspaceInvitationQuotaError):+ """The workspace member allowance in the license is exhausted."""diff --git a/api/services/knowledge/api_key_service.py b/api/services/knowledge/api_key_service.pyindex 875028fab9c..b3feb53ac24 100644--- a/api/services/knowledge/api_key_service.py+++ b/api/services/knowledge/api_key_service.py@@ -5,7 +5,7 @@ from typing import Protocolfrom machinery.context import RequestContextfrom services.auth.api_key_contracts import ApiKeyCache, ApiKeyRecord, ApiKeyResourceNotFoundError-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.knowledge.dataset_access import (DatasetAccess,DatasetAccessDeniedError,diff --git a/api/services/knowledge/dataset_service.py b/api/services/knowledge/dataset_service.pyindex 65e5152fd64..62b057d0032 100644--- a/api/services/knowledge/dataset_service.py+++ b/api/services/knowledge/dataset_service.py@@ -73,7 +73,7 @@ from services.entities.knowledge_entities.rag_pipeline_entities import (KnowledgeConfiguration,RagPipelineDatasetCreateEntity,)-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.errors.chunk import ChildChunkDeleteIndexError, ChildChunkIndexingErrorfrom services.errors.dataset import DatasetNameDuplicateErrorfrom services.errors.document import DocumentIndexingErrordiff --git a/api/services/knowledge/datasets/adapters.py b/api/services/knowledge/datasets/adapters.pyindex 592b43ed1c4..cb6f87ce402 100644--- a/api/services/knowledge/datasets/adapters.py+++ b/api/services/knowledge/datasets/adapters.py@@ -18,7 +18,7 @@ from models.provider_ids import ModelProviderIDfrom repositories.knowledge.dataset_repository import _get_datasetfrom services.app.query_service import AppQueryServicefrom services.enterprise import rbac_service-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.knowledge.dataset_access import DatasetAccessDeniedError, DatasetNotFoundErrorfrom services.knowledge.dataset_read_service import get_dataset_queries, load_dataset_detail, load_dataset_detailsfrom services.knowledge.dataset_service import DatasetPermissionService, DatasetService, DocumentServicediff --git a/api/services/knowledge/documents/adapters.py b/api/services/knowledge/documents/adapters.pyindex 1c2bc398dd5..c0133ecbdfc 100644--- a/api/services/knowledge/documents/adapters.py+++ b/api/services/knowledge/documents/adapters.py@@ -35,7 +35,7 @@ from repositories.knowledge.dataset_read_repository import (from repositories.knowledge.dataset_repository import _get_datasetfrom repositories.knowledge.document_repository import _get_documentfrom services.enterprise import rbac_service-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.errors.document import DocumentIndexingErrorfrom services.file_service import FileServicefrom services.knowledge.dataset_access import DatasetAccessDeniedError, DatasetNotFoundErrordiff --git a/api/services/knowledge/indexing/adapters/estimate.py b/api/services/knowledge/indexing/adapters/estimate.pyindex c09b8c42438..d6279f2d2ea 100644--- a/api/services/knowledge/indexing/adapters/estimate.py+++ b/api/services/knowledge/indexing/adapters/estimate.py@@ -17,8 +17,8 @@ from core.model_manager import ModelInstance, ModelManagerfrom core.plugin.impl.exc import PluginDaemonClientSideErrorfrom core.rag.extractor.entity.extract_setting import ExtractSettingfrom core.rag.index_processor.constant.index_type import IndexTechniqueType+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom core.rag.index_processor.index_processor_base import SummaryIndexSettingDict-from core.rag.index_processor.index_processor_factory import IndexProcessorFactoryfrom core.tools.utils.web_reader_tool import get_image_upload_file_idsfrom enums import DeploymentEditionfrom extensions.ext_storage import storagediff --git a/api/services/knowledge/indexing/adapters/execution.py b/api/services/knowledge/indexing/adapters/execution.pyindex c5578cb97ef..80f81b90b01 100644--- a/api/services/knowledge/indexing/adapters/execution.py+++ b/api/services/knowledge/indexing/adapters/execution.py@@ -22,7 +22,7 @@ from core.rag.datasource.keyword.jieba.jieba import Jiebafrom core.rag.datasource.vdb.vector_factory import Vectorfrom core.rag.embedding.token_counter import calculate_segment_token_countsfrom core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom core.rag.models.document import Documentfrom extensions.application_services.data_sources import build_data_source_credentialsfrom extensions.ext_redis import redis_clientdiff --git a/api/services/setup_adapters.py b/api/services/setup_adapters.pyindex 01f0465ac8e..d14939acc03 100644--- a/api/services/setup_adapters.py+++ b/api/services/setup_adapters.py@@ -3,33 +3,13 @@from contextlib import AbstractContextManagerfrom typing import override-from sqlalchemy.orm import Session, sessionmaker-from extensions.ext_redis import RedisClientWrapper-from services.account_service import RegisterService-from services.setup_service import SetupAccountProvisioner, SetupInput, SetupLock+from services.setup_service import SetupLock_SETUP_LOCK_KEY = "setup:initialize"_SETUP_LOCK_TIMEOUT_SECONDS = 300-class RegisterServiceAccountProvisioner(SetupAccountProvisioner):- def __init__(self, session_factory: sessionmaker[Session]) -> None:- self._session_factory = session_factory-- @override- def provision(self, setup: SetupInput) -> None:- with self._session_factory() as session:- RegisterService.setup(- email=setup.email,- name=setup.name,- password=setup.password,- ip_address=setup.ip_address,- language=setup.language,- session=session,- )--class RedisSetupLock(SetupLock):def __init__(self, *, client: RedisClientWrapper) -> None:self._client = clientdiff --git a/api/services/setup_service.py b/api/services/setup_service.pyindex f12f62796f8..c85b84508ed 100644--- a/api/services/setup_service.py+++ b/api/services/setup_service.py@@ -1,24 +1,10 @@"""Application service for first-time Dify setup."""from contextlib import AbstractContextManager-from dataclasses import dataclassfrom datetime import datetimefrom typing import Protocol--@dataclass(frozen=True, slots=True)-class SetupInput:- email: str- name: str- password: str- ip_address: str- language: str | None---@dataclass(frozen=True, slots=True)-class SetupStatus:- completed: bool- setup_at: datetime | None = None+from services.account.contracts import SetupInput, SetupStatusclass SetupState(Protocol):diff --git a/api/services/trigger/schedule_service.py b/api/services/trigger/schedule_service.pyindex 495674248b1..31fd3f004f4 100644--- a/api/services/trigger/schedule_service.py+++ b/api/services/trigger/schedule_service.py@@ -18,7 +18,7 @@ from libs.schedule_utils import calculate_next_run_at, convert_12h_to_24hfrom models.account import Account, TenantAccountJoinfrom models.trigger import WorkflowSchedulePlanfrom models.workflow import Workflow-from services.errors.account import AccountNotFoundError+from services.account_errors import AccountNotFoundErrorlogger = logging.getLogger(__name__)diff --git a/api/services/web_authentication_adapters.py b/api/services/web_authentication_adapters.pyindex 8cb8982acdb..5e9f1b6e464 100644--- a/api/services/web_authentication_adapters.py+++ b/api/services/web_authentication_adapters.py@@ -7,7 +7,8 @@ from typing import Any, overridefrom libs.helper import RateLimiter, TokenManagerfrom libs.passport import PassportService-from services.account_service import AccountService+from services.account.forgot_password_service import ForgotPasswordSecurityGateway+from services.account.login_service import ConsoleAuthSecurityGatewayfrom services.enterprise.enterprise_service import EnterpriseServicefrom services.entities.auth_audit_entities import LoginFailureReasonfrom services.entities.authentication_entities import StoredAuthenticationToken@@ -136,29 +137,35 @@ class TokenManagerWebAuthenticationGateway(WebAuthenticationTokenGateway):)-class AccountServiceWebAuthenticationSecurityGateway(WebAuthenticationSecurityGateway):- def __init__(self, *, account_service: type[AccountService]) -> None:- self._account_service = account_service+class AccountWebAuthenticationSecurityGateway(WebAuthenticationSecurityGateway):+ def __init__(+ self,+ *,+ password_security: ForgotPasswordSecurityGateway,+ login_security: ConsoleAuthSecurityGateway,+ ) -> None:+ self._password_security = password_security+ self._login_security = login_security@overridedef is_email_send_ip_limited(self, ip_address: str) -> bool:- return bool(self._account_service.is_email_send_ip_limit(ip_address))+ return self._password_security.is_ip_limited(ip_address)@overridedef is_password_reset_verification_limited(self, email: str) -> bool:- return bool(self._account_service.is_forgot_password_error_rate_limit(email))+ return self._password_security.is_verification_limited(email)@overridedef record_password_reset_verification_failure(self, email: str) -> None:- self._account_service.add_forgot_password_error_rate_limit(email)+ self._password_security.record_verification_failure(email)@overridedef reset_password_reset_verification_failures(self, email: str) -> None:- self._account_service.reset_forgot_password_error_rate_limit(email)+ self._password_security.reset_verification_failures(email)@overridedef reset_login_failures(self, email: str) -> None:- self._account_service.reset_login_error_rate_limit(email)+ self._login_security.reset_login_failures(email)class PassportWebAppSessionGateway(WebAppSessionGateway):diff --git a/api/services/workspace/__init__.py b/api/services/workspace/__init__.pynew file mode 100644index 00000000000..d2cb6cc36e6--- /dev/null+++ b/api/services/workspace/__init__.py@@ -0,0 +1 @@+"""Workspace domain modules."""diff --git a/api/services/workspace/contracts.py b/api/services/workspace/contracts.pynew file mode 100644index 00000000000..fe5c7d51e69--- /dev/null+++ b/api/services/workspace/contracts.py@@ -0,0 +1,213 @@+"""Shared workspace data, independent of service implementations."""++from collections.abc import Mapping+from dataclasses import dataclass, field+from datetime import datetime+from typing import Literal, NamedTuple++from enums import CloudPlan+++@dataclass(frozen=True)+class WorkspaceCustomConfig:+ remove_webapp_brand: bool = False+ replace_webapp_logo: str | None = None+++@dataclass(frozen=True)+class WorkspaceCustomConfigChanges:+ remove_webapp_brand: bool | None = None+ replace_webapp_logo: str | None = None+++@dataclass(frozen=True)+class WorkspaceSnapshot:+ id: str+ name: str+ status: str+ created_at: datetime+ role: str | None = None+ custom_config: WorkspaceCustomConfig = field(default_factory=WorkspaceCustomConfig)+ has_privileged_member: bool = False+ current: bool = False+++@dataclass(frozen=True, slots=True)+class WorkspaceMemberWrite:+ workspace_id: str+ account_id: str+ role: str+ account_status: str+ created: bool+++@dataclass(frozen=True, slots=True)+class WorkspaceMemberRemoval:+ account_id: str+ email: str+ account_deleted: bool+++@dataclass(frozen=True)+class WorkspacePage:+ data: tuple[WorkspaceSnapshot, ...]+ total: int+ page: int+ limit: int+ has_more: bool+++@dataclass(frozen=True)+class WorkspaceFeatures:+ can_replace_logo: bool+ credits: "EffectiveCreditPool"+++@dataclass(frozen=True)+class WorkspacePermission:+ workspace_id: str+ allow_member_invite: bool+ allow_owner_transfer: bool+++@dataclass(frozen=True)+class CreatedWorkspace:+ id: str+ name: str+ plan: str+ status: str+ created_at: datetime | None+ updated_at: datetime | None+ encrypt_public_key: str | None+ custom_config: dict[str, object]+++@dataclass(frozen=True)+class WorkspaceMembership:+ workspace_id: str+ account_id: str+ role: str+++@dataclass(frozen=True, slots=True)+class OwnerTransferToken:+ email: str+ code: str+ account_id: str | None = None+++@dataclass(frozen=True, slots=True)+class WorkspaceInvitationResult:+ email: str+ status: Literal["success", "already_member", "failed"]+ token: str | None = None+ message: str | None = None+++@dataclass(frozen=True, slots=True)+class WorkspaceInvitation:+ workspace_id: str+ account_id: str+ email: str+ role: str+ token: str+++@dataclass(frozen=True)+class EffectiveCreditPool:+ plan: CloudPlan | None = None+ pool_type: Literal["paid", "trial"] | None = None+ quota_limit: int | None = None+ quota_used: int | None = None+ exhausted_at: int | None = None+ next_credit_reset_date: int | None = None++ @property+ def remaining_credits(self) -> int | None:+ if self.quota_limit is None or self.quota_used is None:+ return None+ if self.is_unlimited:+ return -1+ return max(0, self.quota_limit - self.quota_used)++ @property+ def is_unlimited(self) -> bool:+ return self.quota_limit == -1++ @property+ def is_exhausted(self) -> bool:+ remaining_credits = self.remaining_credits+ return not self.is_unlimited and (remaining_credits is None or remaining_credits <= 0)+++class WorkspaceRecord(NamedTuple):+ id: str+ name: str | None+ status: str+ created_at: datetime+ last_opened_at: datetime | None+++class WorkspaceSummary(NamedTuple):+ id: str+ name: str | None+ plan: str+ status: str+ created_at: datetime+ last_opened_at: datetime | None+ current: bool+++class WorkspaceMemberRole(NamedTuple):+ id: str+ name: str+++class WorkspaceMemberRecord(NamedTuple):+ id: str+ name: str+ email: str+ avatar: str | None+ last_login_at: datetime | None+ last_active_at: datetime+ created_at: datetime+ status: str+ legacy_role: str++ @property+ def role(self) -> str:+ return self.legacy_role+++@dataclass(frozen=True, slots=True)+class WorkspaceMemberPage:+ members: tuple[WorkspaceMemberRecord, ...]+ total: int+++class WorkspaceMemberRoleSubject(NamedTuple):+ account_id: str+ legacy_role: str+++class WorkspaceMemberSummary(NamedTuple):+ id: str+ name: str+ email: str+ avatar: str | None+ last_login_at: datetime | None+ last_active_at: datetime+ created_at: datetime+ role: str+ roles: tuple[WorkspaceMemberRole, ...]+ status: str+++@dataclass(frozen=True, slots=True)+class WorkspaceCreation:+ id: str+ name: str+ encrypt_public_key: str+ trial_credits: int+ plugin_upgrade_time: int+ plugin_upgrade_settings: Mapping[str, str]diff --git a/api/services/workspace/gateways.py b/api/services/workspace/gateways.pynew file mode 100644index 00000000000..50ea3f5c551--- /dev/null+++ b/api/services/workspace/gateways.py@@ -0,0 +1,511 @@+"""Adapters for workspace plans, features, files, member roles, and provisioning."""++import logging+import secrets+from collections.abc import Mapping, Sequence+from contextlib import AbstractContextManager+from typing import Literal, override+from uuid import uuid4++from sqlalchemy.orm import Session, sessionmaker+from werkzeug.exceptions import Forbidden++from configs import dify_config+from enums import CloudPlan, DeploymentEdition+from events.tenant_event import tenant_was_created+from extensions.ext_redis import RedisClientWrapper+from libs.helper import RateLimiter, TokenManager+from libs.key_providers import generate_key_pair+from libs.workspace_permission import check_workspace_member_invite_permission+from machinery.context import RequestContext+from models.account import (+ Account,+ AccountStatus,+ Tenant,+ TenantAccountRole,+ TenantPluginAutoUpgradeCategory,+)+from repositories.workspace.workspace_repository import WorkspaceRepository+from services.account.adapters import RedisInvitationTokenStore+from services.account_security_gateway import RedisAccountEmailSecurityGateway+from services.billing_service import BillingService+from services.credit_pool_service import CreditPoolBalance, CreditPoolService+from services.enterprise import rbac_service as enterprise_rbac_service+from services.enterprise.enterprise_service import EnterpriseService+from services.enterprise.rbac_service import ListOption, RBACService+from services.entities.account_activation_entities import InvitationToken+from services.entities.account_entities import AccountSnapshot+from services.errors.base import NoPermissionError+from services.errors.workspace import (+ InvalidWorkspaceMemberRoleError,+ OwnerTransferSendRateLimitError,+ WorkspaceInvitationQuotaError,+ WorkspaceMemberLicenseQuotaError,+)+from services.feature_service import FeatureService+from services.file_service import FileService+from services.plugin.plugin_auto_upgrade_service import PluginAutoUpgradeService+from services.system_feature_service import SystemFeatureService+from services.workspace.contracts import (+ CreatedWorkspace,+ EffectiveCreditPool,+ OwnerTransferToken,+ WorkspaceCreation,+ WorkspaceFeatures,+ WorkspaceMemberRemoval,+ WorkspaceMemberRole,+ WorkspaceMemberRoleSubject,+ WorkspaceMemberWrite,+ WorkspacePermission,+)+from services.workspace.member_service import WorkspaceMemberRoleResolver+from services.workspace.service import WorkspaceFeatureGateway, WorkspaceLogoGateway, WorkspacePlanGateway+from tasks.mail_invite_member_task import send_invite_member_mail_task+from tasks.mail_owner_transfer_task import (+ send_new_owner_transfer_notify_email_task,+ send_old_owner_transfer_notify_email_task,+ send_owner_transfer_confirm_task,+)++logger = logging.getLogger(__name__)+++class WorkspaceIdentityGateway:+ """Materialize workspace identities for adapters that require the ORM model."""++ def __init__(self, *, workspaces: WorkspaceRepository) -> None:+ self._workspaces = workspaces++ def get_workspace(self, workspace_id: str) -> Tenant | None:+ return self._workspaces.get_model(workspace_id)+++class WorkspaceOwnerTransferGateway(RedisAccountEmailSecurityGateway):+ def __init__(self, *, redis: RedisClientWrapper) -> None:+ super().__init__(+ redis=redis,+ email_send_ip_limit_per_minute=dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE,+ verification_failure_limit=5,+ verification_lockout_duration=dify_config.OWNER_TRANSFER_LOCKOUT_DURATION,+ verification_key_prefix="owner_transfer_error_rate_limit",+ )+ self._send_limits = RateLimiter(+ prefix="owner_transfer_rate_limit", max_attempts=1, time_window=60, redis_client=redis+ )++ def send_confirmation(self, account: AccountSnapshot, workspace_name: str, language: str) -> str:+ if self._send_limits.is_rate_limited(account.email):+ raise OwnerTransferSendRateLimitError(int(self._send_limits.time_window / 60))+ code = "".join(str(secrets.randbelow(10)) for _ in range(6))+ token = self.issue_token(OwnerTransferToken(account.email, code, account.id))+ send_owner_transfer_confirm_task.delay(language=language, to=account.email, code=code, workspace=workspace_name)+ self._send_limits.increment_rate_limit(account.email)+ return token++ def read_token(self, token: str) -> OwnerTransferToken | None:+ data = TokenManager.get_token_data(token, "owner_transfer")+ if data is None or not isinstance(data.get("email"), str) or not isinstance(data.get("code"), str):+ return None+ return OwnerTransferToken(data["email"], data["code"], data.get("account_id"))++ def issue_token(self, token: OwnerTransferToken) -> str:+ return TokenManager.generate_token(+ account_id=token.account_id,+ email=token.email,+ token_type="owner_transfer",+ additional_data={"code": token.code},+ )++ def revoke_token(self, token: str) -> None:+ TokenManager.revoke_token(token, "owner_transfer")++ def notify(self, *, old_owner: AccountSnapshot, new_owner: AccountSnapshot, workspace_name: str) -> None:+ send_new_owner_transfer_notify_email_task.delay(language="en-US", to=new_owner.email, workspace=workspace_name)+ send_old_owner_transfer_notify_email_task.delay(+ language="en-US", to=old_owner.email, workspace=workspace_name, new_owner_email=new_owner.email+ )+++class DeploymentWorkspaceCreationPolicy:+ def is_workspace_creation_allowed(self) -> bool:+ return SystemFeatureService.is_workspace_creation_allowed()++ def has_workspace_capacity(self) -> bool:+ return SystemFeatureService.get_license().workspaces.is_available()+++def _ensure_role_enabled(role: str) -> None:+ if role == "dataset_operator" and not dify_config.DATASET_OPERATOR_ENABLED:+ raise InvalidWorkspaceMemberRoleError()+++class WorkspaceInvitationGateway:+ def __init__(self, *, tokens: RedisInvitationTokenStore, redis: RedisClientWrapper) -> None:+ self._tokens = tokens+ self._redis = redis++ @property+ def requires_capacity_check(self) -> bool:+ return dify_config.DEPLOYMENT_EDITION in {DeploymentEdition.CLOUD, DeploymentEdition.ENTERPRISE}++ def acquire(self, workspace_id: str) -> AbstractContextManager[object]:+ return self._redis.lock(f"workspace_member_invite:{workspace_id}", timeout=60)++ def ensure_role_enabled(self, role: str) -> None:+ _ensure_role_enabled(role)++ def check_invitation_quota(self, workspace_id: str) -> None:+ """Admit a single invitation using the advertised plan and license limits.++ Unlike batch capacity checks, this gate also applies to reinvitations+ and uses the billing-reported member count.+ """+ features = FeatureService.get_features(tenant_id=workspace_id, exclude_vector_space=True)+ if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:+ if 0 < features.members.limit <= features.members.size:+ raise WorkspaceInvitationQuotaError()+ if features.workspace_members.enabled and not features.workspace_members.is_available(1):+ raise WorkspaceMemberLicenseQuotaError()++ def check_capacity(self, workspace_id: str, *, current_members: int, new_members: int, new_accounts: int) -> None:+ if dify_config.DEPLOYMENT_EDITION not in {DeploymentEdition.CLOUD, DeploymentEdition.ENTERPRISE}:+ return+ features = FeatureService.get_features(tenant_id=workspace_id, exclude_vector_space=True)+ if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.ENTERPRISE:+ quota = features.workspace_members+ if quota.enabled and not quota.is_available(new_members):+ raise WorkspaceMemberLicenseQuotaError()+ if new_accounts and not SystemFeatureService.get_license().seats.is_available(new_accounts):+ raise WorkspaceInvitationQuotaError(seats=True)+ elif 0 < features.members.limit < current_members + new_members:+ raise WorkspaceInvitationQuotaError()++ def ensure_allowed(self, workspace_id: str) -> None:+ try:+ check_workspace_member_invite_permission(workspace_id)+ except Forbidden as error:+ raise NoPermissionError(error.description) from error++ def create(self, invitation: InvitationToken) -> str:+ return self._tokens.create(invitation)++ def send(self, *, language: str, email: str, token: str, inviter_name: str, workspace_name: str) -> None:+ send_invite_member_mail_task.delay(+ language=language,+ to=email,+ token=token,+ inviter_name=inviter_name,+ workspace_name=workspace_name,+ )+++class DeploymentWorkspaceMemberAccessGateway:+ def __init__(self, *, session_factory: sessionmaker[Session]) -> None:+ self._session_factory = session_factory++ def ensure_role_enabled(self, role: str) -> None:+ _ensure_role_enabled(role)++ @property+ def rbac_enabled(self) -> bool:+ return dify_config.RBAC_ENABLED++ def permission_keys(self, workspace_id: str, actor_id: str) -> set[str]:+ with self._session_factory() as session:+ permissions = RBACService.MyPermissions.get(workspace_id, actor_id, session=session)+ return set(permissions.workspace.permission_keys)++ def is_owner(self, workspace_id: str, actor_id: str, member_id: str) -> bool:+ with self._session_factory() as session:+ roles = RBACService.MemberRoles.get(workspace_id, actor_id, member_id, session=session).roles+ return any(+ role.is_builtin and role.category == "global_system_default" and role.role_tag == "owner"+ for role in roles+ )++ @staticmethod+ def _role_id(workspace_id: str, actor_id: str, tag: str) -> str:+ roles = RBACService.Roles.list(+ workspace_id, actor_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 == tag:+ return str(role.id)+ raise ValueError(f"Builtin RBAC role not found for tag {tag!r} in tenant {workspace_id}")++ def owner_id(self, workspace_id: str, actor_id: str) -> str:+ members = RBACService.Roles.members(+ tenant_id=workspace_id,+ account_id=actor_id,+ role_id=self._role_id(workspace_id, actor_id, "owner"),+ options=ListOption(page_number=1, results_per_page=1),+ ).data+ if not members:+ raise ValueError(f"Workspace RBAC owner not found for tenant {workspace_id}.")+ return members[0].account_id++ def assign_role(self, workspace_id: str, actor_id: str, member_id: str, role_id: str) -> None:+ with self._session_factory() as session:+ RBACService.MemberRoles.replace(+ tenant_id=workspace_id,+ account_id=actor_id,+ member_account_id=member_id,+ role_ids=[role_id],+ session=session,+ )+ session.commit()++ def change_role(self, workspace_id: str, actor_id: str, member_id: str, role: TenantAccountRole) -> None:+ if not TenantAccountRole.is_non_owner_role(role):+ raise InvalidWorkspaceMemberRoleError("Owner changes require ownership transfer.")+ self.assign_role(workspace_id, actor_id, member_id, self._role_id(workspace_id, actor_id, role.value))++ def transfer_owner(self, workspace_id: str, actor_id: str, member_id: str) -> None:+ owner_role_id = self._role_id(workspace_id, actor_id, "owner")+ old_owner_id = self.owner_id(workspace_id, actor_id)+ no_access_id = self._role_id(workspace_id, actor_id, "no_access")+ # With RBAC enabled these calls update the enterprise service, not the local+ # Session. Complete both before the repository commits local owner changes.+ with self._session_factory() as session:+ current = RBACService.MemberRoles.get(workspace_id, actor_id, old_owner_id, session=session).roles+ remaining = [str(item.id) for item in current if str(item.id) != owner_role_id]+ RBACService.MemberRoles.replace(+ tenant_id=workspace_id,+ account_id=actor_id,+ member_account_id=old_owner_id,+ role_ids=remaining or [no_access_id],+ session=session,+ )+ RBACService.MemberRoles.replace(+ tenant_id=workspace_id,+ account_id=actor_id,+ member_account_id=member_id,+ role_ids=[owner_role_id],+ session=session,+ )++ def membership_changed(self, membership: WorkspaceMemberWrite, operator_account_id: str | None) -> None:+ if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:+ BillingService.clean_billing_info_cache(membership.workspace_id)+ if (+ membership.created+ and self.rbac_enabled+ and membership.role != TenantAccountRole.OWNER+ and membership.account_status != AccountStatus.PENDING+ ):+ from tasks.initialize_created_app_rbac_access_task import sync_joined_workspace_member_rbac_access_task++ sync_joined_workspace_member_rbac_access_task.delay(+ membership.workspace_id,+ membership.account_id,+ operator_account_id=operator_account_id,+ )++ def member_removed(self, workspace_id: str, removal: WorkspaceMemberRemoval) -> None:+ if removal.account_deleted:+ logger.info("Deleted orphaned pending account: account_id=%s, email=%s", removal.account_id, removal.email)+ if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:+ BillingService.clean_billing_info_cache(workspace_id)+ from services.enterprise.account_deletion_sync import sync_workspace_member_removal++ if not sync_workspace_member_removal(+ workspace_id=workspace_id, member_id=removal.account_id, source="workspace_member_removed"+ ):+ logger.warning(+ "Enterprise workspace member removal sync failed: workspace_id=%s, member_id=%s",+ workspace_id,+ removal.account_id,+ )+ if self.rbac_enabled:+ RBACService.MemberRoles.delete_rbac_bindings(tenant_id=workspace_id, account_id=removal.account_id)+++class DeploymentWorkspacePlanGateway(WorkspacePlanGateway):+ """Resolve workspace plans using deployment-specific Billing and Feature sources."""++ @override+ def resolve_many(self, workspace_ids: Sequence[str]) -> Mapping[str, str]:+ ids = tuple(workspace_ids)+ if not ids:+ return {}++ is_enterprise_only = dify_config.DEPLOYMENT_EDITION == DeploymentEdition.ENTERPRISE+ if is_enterprise_only:+ return dict.fromkeys(ids, str(CloudPlan.SANDBOX))++ is_saas = dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD+ bulk_plans = BillingService.get_plan_bulk(ids) if is_saas else {}+ if is_saas and not bulk_plans:+ logger.warning("get_plan_bulk returned empty result, falling back to FeatureService")++ resolved: dict[str, str] = {}+ for workspace_id in ids:+ tenant_plan = bulk_plans.get(workspace_id)+ if tenant_plan:+ resolved[workspace_id] = tenant_plan["plan"] or CloudPlan.SANDBOX+ continue++ features = FeatureService.get_features(workspace_id, exclude_vector_space=True)+ resolved[workspace_id] = features.billing.subscription.plan or CloudPlan.SANDBOX++ return resolved+++class DeploymentWorkspaceFeatureGateway(WorkspaceFeatureGateway):+ @override+ def get_features(self, workspace_id: str) -> WorkspaceFeatures:+ features = FeatureService.get_features(workspace_id, exclude_vector_space=True)+ credits = EffectiveCreditPool()+ if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:+ credits = self._credit_pool(+ workspace_id, CloudPlan(features.billing.subscription.plan), features.next_credit_reset_date+ )+ return WorkspaceFeatures(can_replace_logo=features.can_replace_logo, credits=credits)++ @override+ def get_effective_credit_pool(self, workspace_id: str) -> EffectiveCreditPool:+ if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:+ return EffectiveCreditPool()+ billing = BillingService.get_info(workspace_id, exclude_vector_space=True)+ return self._credit_pool(+ workspace_id, CloudPlan(billing["subscription"]["plan"]), billing.get("next_credit_reset_date")+ )++ @staticmethod+ def _credit_pool(workspace_id: str, plan: CloudPlan, reset_date: int | None) -> EffectiveCreditPool:+ # In Cloud, CreditPoolService reads the billing quota API, without an ORM Session.+ pool = None+ pool_type: Literal["paid", "trial"] = "trial"+ if plan != CloudPlan.SANDBOX:+ paid = CreditPoolService.get_pool(tenant_id=workspace_id, pool_type="paid")+ if paid is not None and (paid.quota_limit == -1 or paid.quota_limit > paid.quota_used):+ pool, pool_type = paid, "paid"+ if pool is None:+ pool = CreditPoolService.get_pool(tenant_id=workspace_id, pool_type="trial")+ if pool is None:+ return EffectiveCreditPool(plan=plan, next_credit_reset_date=reset_date)+ exhausted_at = pool.exhausted_at if isinstance(pool, CreditPoolBalance) else None+ if not (+ isinstance(exhausted_at, int)+ and exhausted_at > 0+ and pool.quota_limit > 0+ and pool.quota_used >= pool.quota_limit+ ):+ exhausted_at = None+ return EffectiveCreditPool(+ plan=plan,+ pool_type=pool_type,+ quota_limit=pool.quota_limit,+ quota_used=pool.quota_used,+ exhausted_at=exhausted_at,+ next_credit_reset_date=reset_date,+ )++ @override+ def logo_url(self, workspace_id: str) -> str:+ return f"{dify_config.FILES_URL}/files/workspaces/{workspace_id}/webapp-logo"++ @override+ def get_permission(self, workspace_id: str) -> WorkspacePermission:+ permission = EnterpriseService.WorkspacePermissionService.get_permission(workspace_id)+ return WorkspacePermission(+ workspace_id=permission.workspace_id,+ allow_member_invite=permission.allow_member_invite,+ allow_owner_transfer=permission.allow_owner_transfer,+ )+++class WorkspaceFileGateway(WorkspaceLogoGateway):+ def __init__(self, *, files: FileService) -> None:+ self._files = files++ @override+ def upload(self, context: RequestContext, *, filename: str, content: bytes, mimetype: str) -> str:+ # FileService only needs the admitted account ID and its explicit tenant ID.+ owner = Account(name="", email="")+ owner.id = context.account_id+ return self._files.upload_file(+ filename=filename,+ content=content,+ mimetype=mimetype,+ user=owner,+ tenant_id=context.active_workspace_id,+ ).id+++class DeploymentWorkspaceMemberRoleResolver(WorkspaceMemberRoleResolver):+ """Preserve deployment-specific legacy and enterprise role behavior."""++ @override+ def resolve_many(+ self,+ workspace_id: str,+ actor_account_id: str,+ subjects: Sequence[WorkspaceMemberRoleSubject],+ ) -> Mapping[str, Sequence[WorkspaceMemberRole]]:+ role_subjects = tuple(subjects)+ if not role_subjects:+ return {}++ if not dify_config.RBAC_ENABLED:+ return {+ subject.account_id: (WorkspaceMemberRole(id=subject.legacy_role, name=subject.legacy_role),)+ for subject in role_subjects+ }++ member_roles = enterprise_rbac_service.RBACService.MemberRoles.batch_get(+ workspace_id,+ actor_account_id,+ [subject.account_id for subject in role_subjects],+ )+ return {+ item.account_id: tuple(WorkspaceMemberRole(id=role.id, name=role.name) for role in item.roles)+ for item in member_roles+ }+++class WorkspaceProvisioningEffectsGateway:+ """Prepare external resources and publish committed workspace creation."""++ def __init__(self, *, session_factory: sessionmaker[Session]) -> None:+ self._session_factory = session_factory++ def prepare(self, name: str) -> WorkspaceCreation:+ workspace_id = str(uuid4())+ return WorkspaceCreation(+ id=workspace_id,+ name=name,+ encrypt_public_key=generate_key_pair(workspace_id),+ trial_credits=dify_config.HOSTED_POOL_CREDITS,+ plugin_upgrade_time=PluginAutoUpgradeService.default_upgrade_time_of_day(workspace_id),+ plugin_upgrade_settings={+ category.value: PluginAutoUpgradeService.default_strategy_setting_for_category(category).value+ for category in TenantPluginAutoUpgradeCategory+ },+ )++ def bind_owner(self, workspace_id: str, account_id: str) -> None:+ if not dify_config.RBAC_ENABLED:+ return+ role_id = DeploymentWorkspaceMemberAccessGateway._role_id(workspace_id, account_id, "owner")+ # RBAC uses the enterprise API here. Its shared signature requires a+ # Session, but this call does not perform local database queries.+ with self._session_factory() as session:+ RBACService.MemberRoles.replace(+ tenant_id=workspace_id,+ account_id=account_id,+ member_account_id=account_id,+ role_ids=[role_id],+ session=session,+ )++ def created(self, workspace: CreatedWorkspace, *, owner_id: str | None) -> None:+ if owner_id is not None and dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:+ BillingService.clean_billing_info_cache(workspace.id)+ tenant_was_created.send(workspace)++ def join_default_workspace(self, account_id: str) -> None:+ if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.ENTERPRISE:+ from services.enterprise.enterprise_service import try_join_default_workspace++ try_join_default_workspace(account_id)diff --git a/api/services/workspace/member_service.py b/api/services/workspace/member_service.pynew file mode 100644index 00000000000..e766c47796d--- /dev/null+++ b/api/services/workspace/member_service.py@@ -0,0 +1,532 @@+"""Workspace membership, invitation and ownership use cases with application-owned ports."""++from collections.abc import Mapping, Sequence+from contextlib import AbstractContextManager+from typing import Protocol++from enums.account import TenantAccountRole+from machinery.context import RequestContext+from services.account_errors import AccountNotFoundError+from services.account_ports import AccountSnapshotQuery+from services.entities.account_activation_entities import InvitationToken+from services.entities.account_entities import AccountSnapshot+from services.errors.base import NoPermissionError+from services.errors.workspace import (+ AccountAlreadyInTenantError,+ CannotOperateSelfError,+ InvalidActionError,+ InvalidOwnerTransferCodeError,+ InvalidOwnerTransferEmailError,+ InvalidOwnerTransferTokenError,+ InvalidWorkspaceMemberRoleError,+ MemberNotInTenantError,+ OwnerTransferSendIPLimitedError,+ OwnerTransferVerificationLimitError,+ RoleAlreadyAssignedError,+ WorkspaceAlreadyHasOwnerError,+ WorkspaceNotFoundError,+)+from services.workspace.contracts import (+ OwnerTransferToken,+ WorkspaceInvitation,+ WorkspaceInvitationResult,+ WorkspaceMemberPage,+ WorkspaceMemberRecord,+ WorkspaceMemberRemoval,+ WorkspaceMemberRole,+ WorkspaceMemberRoleSubject,+ WorkspaceMembership,+ WorkspaceMemberSummary,+ WorkspaceMemberWrite,+ WorkspaceSnapshot,+)+++class WorkspaceMemberQuery(Protocol):+ def list_for_workspace(+ self, workspace_id: str, *, role: TenantAccountRole | None = None+ ) -> Sequence[WorkspaceMemberRecord]: ...+++class WorkspaceMemberRoleResolver(Protocol):+ def resolve_many(+ self,+ workspace_id: str,+ actor_account_id: str,+ subjects: Sequence[WorkspaceMemberRoleSubject],+ ) -> Mapping[str, Sequence[WorkspaceMemberRole]]: ...+++class WorkspaceMemberQueryService:+ def __init__(+ self,+ *,+ members: WorkspaceMemberQuery,+ roles: WorkspaceMemberRoleResolver,+ ) -> None:+ self._members = members+ self._roles = roles++ def list_members(+ self, workspace_id: str, *, dataset_operators_only: bool = False+ ) -> tuple[WorkspaceMemberRecord, ...]:+ role = TenantAccountRole.DATASET_OPERATOR if dataset_operators_only else None+ return tuple(self._members.list_for_workspace(workspace_id, role=role))++ def list_page(self, context: RequestContext, *, page: int, limit: int) -> WorkspaceMemberPage:+ records = self.list_members(context.active_workspace_id)+ start = (page - 1) * limit+ return WorkspaceMemberPage(members=records[start : start + limit], total=len(records))++ def list_current(self, context: RequestContext) -> tuple[WorkspaceMemberSummary, ...]:+ workspace_id = context.active_workspace_id++ records = tuple(self._members.list_for_workspace(workspace_id))+ role_subjects = tuple(+ WorkspaceMemberRoleSubject(account_id=record.id, legacy_role=record.legacy_role) for record in records+ )++ # The repository closes its read Session before role resolution+ # performs enterprise I/O.+ roles_by_member = self._roles.resolve_many(workspace_id, context.account_id, role_subjects)++ return tuple(+ WorkspaceMemberSummary(+ id=record.id,+ name=record.name,+ email=record.email,+ avatar=record.avatar,+ last_login_at=record.last_login_at,+ last_active_at=record.last_active_at,+ created_at=record.created_at,+ role=record.legacy_role,+ roles=tuple(roles_by_member.get(record.id, ())),+ status=record.status,+ )+ for record in records+ )+++class WorkspaceMemberStore(Protocol):+ def get(self, workspace_id: str) -> WorkspaceSnapshot | None: ...++ def member_role(self, workspace_id: str, account_id: str | None) -> TenantAccountRole | None: ...++ def owner_id(self, workspace_id: str) -> str | None: ...++ def upsert_member(self, *, workspace_id: str, account_id: str, role: TenantAccountRole) -> WorkspaceMemberWrite: ...++ def remove_member(self, *, workspace_id: str, account_id: str, owner_id: str) -> WorkspaceMemberRemoval: ...++ def update_member_role(self, *, workspace_id: str, account_id: str, role: TenantAccountRole) -> None: ...+++class WorkspaceMemberAccessGateway(Protocol):+ @property+ def rbac_enabled(self) -> bool: ...++ def ensure_role_enabled(self, role: str) -> None: ...++ def permission_keys(self, workspace_id: str, actor_id: str) -> set[str]: ...++ def is_owner(self, workspace_id: str, actor_id: str, member_id: str) -> bool: ...++ def owner_id(self, workspace_id: str, actor_id: str) -> str: ...++ def assign_role(self, workspace_id: str, actor_id: str, member_id: str, role_id: str) -> None: ...++ def change_role(self, workspace_id: str, actor_id: str, member_id: str, role: TenantAccountRole) -> None: ...++ def transfer_owner(self, workspace_id: str, actor_id: str, member_id: str) -> None: ...++ def membership_changed(self, membership: WorkspaceMemberWrite, operator_account_id: str | None) -> None: ...++ def member_removed(self, workspace_id: str, removal: WorkspaceMemberRemoval) -> None: ...+++class WorkspaceMemberService:+ def __init__(+ self, *, workspaces: WorkspaceMemberStore, accounts: AccountSnapshotQuery, access: WorkspaceMemberAccessGateway+ ) -> None:+ self._workspaces = workspaces+ self._accounts = accounts+ self._access = access++ @property+ def rbac_enabled(self) -> bool:+ return self._access.rbac_enabled++ def get_role(self, workspace_id: str, account_id: str | None) -> TenantAccountRole | None:+ return self._workspaces.member_role(workspace_id, account_id)++ def check_permission(self, workspace_id: str, operator_id: str, member_id: str | None, action: str) -> None:+ if action not in {"add", "remove", "update"}:+ raise InvalidActionError("Invalid action.")+ if member_id == operator_id:+ raise CannotOperateSelfError("Cannot operate self.")+ if self._access.rbac_enabled:+ permission = "workspace.member.manage" if action in {"add", "remove"} else "workspace.role.manage"+ if permission not in self._access.permission_keys(workspace_id, operator_id):+ raise NoPermissionError(f"No permission to {action} member.")+ if action == "remove" and member_id and self._access.is_owner(workspace_id, operator_id, member_id):+ raise NoPermissionError(f"No permission to {action} member.")+ return+ role = self.get_role(workspace_id, operator_id)+ if role not in {TenantAccountRole.OWNER, TenantAccountRole.ADMIN}:+ raise NoPermissionError(f"No permission to {action} member.")+ if (+ action == "remove"+ and role == TenantAccountRole.ADMIN+ and member_id+ and self.get_role(workspace_id, member_id) == TenantAccountRole.OWNER+ ):+ raise NoPermissionError(f"No permission to {action} member.")++ def join_member(+ self,+ *,+ workspace_id: str,+ account_id: str,+ email: str,+ role: TenantAccountRole,+ operator_account_id: str | None,+ ) -> WorkspaceMembership:+ """Add or update a member and synchronize their workspace access.++ Raises:+ WorkspaceNotFoundError: The workspace is missing or is not active.+ AccountNotFoundError: The account is missing or its email does not match.+ WorkspaceAlreadyHasOwnerError: An owner is requested but the workspace+ already has one.+ """+ workspace = self._workspaces.get(workspace_id)+ if workspace is None or workspace.status != "normal":+ raise WorkspaceNotFoundError()+ account = self._accounts.get(account_id)+ if account is None or account.email != email:+ raise AccountNotFoundError()+ if role == TenantAccountRole.OWNER and self._workspaces.owner_id(workspace_id) is not None:+ raise WorkspaceAlreadyHasOwnerError("Tenant already has an owner.")+ membership = self._workspaces.upsert_member(workspace_id=workspace_id, account_id=account_id, role=role)+ self._access.membership_changed(membership, operator_account_id)+ return WorkspaceMembership(workspace_id, account_id, role.value)++ def assign_role(self, workspace_id: str, operator_id: str, member_id: str, role_id: str) -> None:+ self._access.assign_role(workspace_id, operator_id, member_id, role_id)++ def remove(self, workspace_id: str, account_id: str, operator_id: str) -> None:+ """Remove a member and transfer their resources to the workspace owner.++ Raises:+ AccountNotFoundError: The member account does not exist.+ CannotOperateSelfError: The operator tries to remove themselves.+ NoPermissionError: The operator cannot remove the member.+ MemberNotInTenantError: The account is not a member of the workspace.+ ValueError: The workspace has no owner to receive the member's resources.+ """+ if self._accounts.get(account_id) is None:+ raise AccountNotFoundError()+ self.check_permission(workspace_id, operator_id, account_id, "remove")+ if self.get_role(workspace_id, account_id) is None:+ raise MemberNotInTenantError("Member not in tenant.")+ owner_id = (+ self._access.owner_id(workspace_id, operator_id)+ if self._access.rbac_enabled+ else self._workspaces.owner_id(workspace_id)+ )+ if owner_id is None:+ raise ValueError(f"Workspace owner not found for tenant {workspace_id}.")+ removal = self._workspaces.remove_member(workspace_id=workspace_id, account_id=account_id, owner_id=owner_id)+ self._access.member_removed(workspace_id, removal)++ def update_role(self, workspace_id: str, member_id: str, new_role: str, operator_id: str) -> None:+ if not TenantAccountRole.is_valid_role(new_role):+ raise InvalidWorkspaceMemberRoleError()+ self._access.ensure_role_enabled(new_role)+ if self._accounts.get(member_id) is None:+ raise AccountNotFoundError()+ self.check_permission(workspace_id, operator_id, member_id, "update")+ role = TenantAccountRole(new_role)+ previous = self.get_role(workspace_id, member_id)+ if previous is None:+ raise MemberNotInTenantError("Member not in tenant.")+ # RBAC ownership can be ahead of local membership after a failed local commit.+ if previous == TenantAccountRole.OWNER or (+ self._access.rbac_enabled and self._access.is_owner(workspace_id, operator_id, member_id)+ ):+ raise NoPermissionError("No permission to update member.")+ if role == TenantAccountRole.OWNER and (+ self.get_role(workspace_id, operator_id) != TenantAccountRole.OWNER+ or (self._access.rbac_enabled and not self._access.is_owner(workspace_id, operator_id, operator_id))+ ):+ raise NoPermissionError("No permission to update member.")+ if previous == role:+ raise RoleAlreadyAssignedError("The provided role is already assigned to the member.")+ if self._access.rbac_enabled:+ if role == TenantAccountRole.OWNER:+ self._access.transfer_owner(workspace_id, operator_id, member_id)+ else:+ self._access.change_role(workspace_id, operator_id, member_id, role)+ self._workspaces.update_member_role(workspace_id=workspace_id, account_id=member_id, role=role)+++class InvitedAccountRegistration(Protocol):+ def get_account_by_id(self, account_id: str) -> AccountSnapshot | None: ...++ def get_account_by_email_with_case_fallback(self, email: str) -> AccountSnapshot | None: ...++ def register(+ self,+ email: str,+ name: str,+ *,+ language: str | None,+ status: str,+ is_setup: bool,+ check_normalized_email: bool,+ ) -> AccountSnapshot: ...+++class InvitationWorkspaceStore(Protocol):+ def get(self, workspace_id: str) -> WorkspaceSnapshot | None: ...++ def switch(self, *, account_id: str, workspace_id: str) -> WorkspaceSnapshot: ...++ def count_members(self, workspace_id: str) -> int: ...+++class WorkspaceInvitationDelivery(Protocol):+ @property+ def requires_capacity_check(self) -> bool: ...++ def acquire(self, workspace_id: str) -> AbstractContextManager[object]: ...++ def ensure_role_enabled(self, role: str) -> None: ...++ def check_capacity(+ self, workspace_id: str, *, current_members: int, new_members: int, new_accounts: int+ ) -> None: ...++ def ensure_allowed(self, workspace_id: str) -> None: ...++ def check_invitation_quota(self, workspace_id: str) -> None: ...++ def create(self, invitation: InvitationToken) -> str: ...++ def send(self, *, language: str, email: str, token: str, inviter_name: str, workspace_name: str) -> None: ...+++class WorkspaceInvitationService:+ def __init__(+ self,+ *,+ accounts: InvitedAccountRegistration,+ workspaces: InvitationWorkspaceStore,+ members: WorkspaceMemberService,+ invitations: WorkspaceInvitationDelivery,+ ) -> None:+ self._accounts = accounts+ self._workspaces = workspaces+ self._members = members+ self._invitations = invitations++ def check_invitation_quota(self, context: RequestContext) -> None:+ self._invitations.check_invitation_quota(context.active_workspace_id)++ def invite_many(+ self, context: RequestContext, *, emails: Sequence[str], language: str | None, role: str+ ) -> tuple[WorkspaceInvitationResult, ...]:+ if not self._members.rbac_enabled and (not TenantAccountRole.is_valid_role(role) or role == "owner"):+ raise InvalidWorkspaceMemberRoleError()+ self._invitations.ensure_role_enabled(role)+ workspace_id = context.active_workspace_id+ self._invitations.ensure_allowed(workspace_id)+ results: list[WorkspaceInvitationResult] = []+ with self._invitations.acquire(workspace_id):+ if self._invitations.requires_capacity_check:+ new_members, new_accounts = 0, 0+ for email in emails:+ account = self._accounts.get_account_by_email_with_case_fallback(email)+ if account is None:+ new_accounts += 1+ new_members += 1+ elif self._members.get_role(workspace_id, account.id) is None:+ new_members += 1+ if new_members:+ self._invitations.check_capacity(+ workspace_id,+ current_members=self._workspaces.count_members(workspace_id),+ new_members=new_members,+ new_accounts=new_accounts,+ )+ for email in emails:+ try:+ invitation = self.invite(context, email, language, role)+ results.append(WorkspaceInvitationResult(email, "success", token=invitation.token))+ except AccountAlreadyInTenantError:+ results.append(+ WorkspaceInvitationResult(email, "already_member", message="Account already in workspace.")+ )+ except Exception as error:+ results.append(WorkspaceInvitationResult(email, "failed", message=str(error)))+ return tuple(results)++ def invite(+ self,+ context: RequestContext,+ email: str,+ language: str | None,+ role: str = "normal",+ ) -> WorkspaceInvitation:+ workspace_id = context.active_workspace_id+ inviter_id = context.account_id+ inviter = self._accounts.get_account_by_id(inviter_id)+ workspace = self._workspaces.get(workspace_id)+ if inviter is None:+ raise ValueError("Inviter is required")+ if workspace is None:+ raise WorkspaceNotFoundError()+ self._invitations.ensure_allowed(workspace_id)+ normalized_email = email.lower()+ join_role = TenantAccountRole.NORMAL if self._members.rbac_enabled else TenantAccountRole(role)+ account = self._accounts.get_account_by_email_with_case_fallback(email)+ requires_setup = False+ if account is None:+ self._members.check_permission(workspace_id, inviter_id, None, "add")+ account = self._accounts.register(+ email=normalized_email,+ name=normalized_email.split("@")[0],+ language=language,+ status="pending",+ is_setup=True,+ check_normalized_email=True,+ )+ self._members.join_member(+ workspace_id=workspace_id,+ account_id=account.id,+ email=account.email,+ role=join_role,+ operator_account_id=inviter_id,+ )+ self._workspaces.switch(account_id=account.id, workspace_id=workspace_id)+ requires_setup = True+ else:+ self._members.check_permission(workspace_id, inviter_id, account.id, "add")+ previous_role = self._members.get_role(workspace_id, account.id)+ requires_setup = account.status == "pending"+ if previous_role is None and (requires_setup or self._members.rbac_enabled):+ self._members.join_member(+ workspace_id=workspace_id,+ account_id=account.id,+ email=account.email,+ role=join_role,+ operator_account_id=inviter_id,+ )+ if account.status != "pending":+ if self._members.rbac_enabled and previous_role is None:+ self._members.assign_role(workspace_id, inviter_id, account.id, role)+ if previous_role is not None or self._members.rbac_enabled:+ raise AccountAlreadyInTenantError("Account already in tenant.")+ if self._members.rbac_enabled:+ self._members.assign_role(workspace_id, inviter_id, account.id, role)+ token = self._invitations.create(InvitationToken(account.id, account.email, workspace_id, role, requires_setup))+ self._invitations.send(+ language=account.interface_language or "en-US",+ email=account.email,+ token=token,+ inviter_name=inviter.name,+ workspace_name=workspace.name,+ )+ return WorkspaceInvitation(workspace_id, account.id, normalized_email, role, token)+++class OwnerTransferGateway(Protocol):+ def is_ip_limited(self, ip_address: str) -> bool: ...++ def is_verification_limited(self, email: str) -> bool: ...++ def record_verification_failure(self, email: str) -> None: ...++ def reset_verification_failures(self, email: str) -> None: ...++ def send_confirmation(self, account: AccountSnapshot, workspace_name: str, language: str) -> str: ...++ def read_token(self, token: str) -> OwnerTransferToken | None: ...++ def issue_token(self, token: OwnerTransferToken) -> str: ...++ def revoke_token(self, token: str) -> None: ...++ def notify(self, *, old_owner: AccountSnapshot, new_owner: AccountSnapshot, workspace_name: str) -> None: ...+++class WorkspaceOwnerTransferService:+ def __init__(+ self,+ *,+ accounts: AccountSnapshotQuery,+ workspaces: WorkspaceMemberStore,+ members: WorkspaceMemberService,+ challenges: OwnerTransferGateway,+ ) -> None:+ self._accounts = accounts+ self._workspaces = workspaces+ self._members = members+ self._challenges = challenges++ def _owner(self, context: RequestContext) -> AccountSnapshot:+ if self._members.get_role(context.active_workspace_id, context.account_id) != TenantAccountRole.OWNER:+ raise NoPermissionError("Only the workspace owner can transfer ownership.")+ owner = self._accounts.get(context.account_id)+ if owner is None:+ raise AccountNotFoundError()+ return owner++ def send_code(self, context: RequestContext, *, ip_address: str, language: str | None) -> str:+ if self._challenges.is_ip_limited(ip_address):+ raise OwnerTransferSendIPLimitedError()+ owner = self._owner(context)+ workspace = self._workspaces.get(context.active_workspace_id)+ if workspace is None:+ raise WorkspaceNotFoundError()+ return self._challenges.send_confirmation(+ owner, workspace.name, "zh-Hans" if language == "zh-Hans" else "en-US"+ )++ def verify_code(self, context: RequestContext, *, token: str, code: str) -> tuple[str, str]:+ owner = self._owner(context)+ if self._challenges.is_verification_limited(owner.email):+ raise OwnerTransferVerificationLimitError()+ challenge = self._challenge(token, owner.email)+ if challenge.code != code:+ self._challenges.record_verification_failure(owner.email)+ raise InvalidOwnerTransferCodeError()+ self._challenges.revoke_token(token)+ new_token = self._challenges.issue_token(OwnerTransferToken(owner.email, code))+ self._challenges.reset_verification_failures(owner.email)+ return owner.email, new_token++ def _challenge(self, token: str, email: str) -> OwnerTransferToken:+ challenge = self._challenges.read_token(token)+ if challenge is None:+ raise InvalidOwnerTransferTokenError()+ if challenge.email != email:+ raise InvalidOwnerTransferEmailError()+ return challenge++ def transfer(self, context: RequestContext, *, member_id: str, token: str) -> None:+ owner = self._owner(context)+ if owner.id == member_id:+ raise CannotOperateSelfError("Cannot transfer ownership to self.")+ self._challenge(token, owner.email)+ self._challenges.revoke_token(token)+ member = self._accounts.get(member_id)+ if member is None:+ raise AccountNotFoundError()+ if self._members.get_role(context.active_workspace_id, member_id) is None:+ raise MemberNotInTenantError("The new owner is not a workspace member.")+ workspace = self._workspaces.get(context.active_workspace_id)+ if workspace is None:+ raise WorkspaceNotFoundError()+ self._members.update_role(workspace.id, member.id, "owner", owner.id)+ self._challenges.notify(old_owner=owner, new_owner=member, workspace_name=workspace.name)diff --git a/api/services/workspace/provisioning_service.py b/api/services/workspace/provisioning_service.pynew file mode 100644index 00000000000..1364364653b--- /dev/null+++ b/api/services/workspace/provisioning_service.py@@ -0,0 +1,196 @@+"""Internal workspace creation and membership use cases."""++from collections.abc import Callable+from typing import Protocol++from enums.account import TenantAccountRole+from services.account.contracts import AccountCreation+from services.account_errors import AccountNormalizedEmailAlreadyInUseError, AccountNotFoundError+from services.entities.account_entities import AccountSnapshot+from services.errors.workspace import (+ InvalidWorkspaceMemberRoleError,+ WorkSpaceNotAllowedCreateError,+ WorkspaceOwnerNotFoundError,+ WorkspacesLimitExceededError,+)+from services.workspace.contracts import CreatedWorkspace, WorkspaceCreation, WorkspaceMembership+++class WorkspaceOwnerQuery(Protocol):+ def find_first_by_email(self, email: str) -> AccountSnapshot | None: ...++ def get(self, account_id: str) -> AccountSnapshot | None: ...++ def normalized_email_exists(self, email: str) -> bool: ...+++class WorkspaceCreationPolicy(Protocol):+ def is_workspace_creation_allowed(self) -> bool: ...++ def has_workspace_capacity(self) -> bool: ...+++class WorkspaceMembershipQuery(Protocol):+ def list_ids_for_account(self, account_id: str) -> tuple[str, ...]: ...++ def has_active_for_account(self, account_id: str) -> bool: ...+++class WorkspaceProvisioningStore(Protocol):+ def provision(+ self,+ prepare: Callable[[], WorkspaceCreation],+ *,+ owner_id: str | None,+ account: AccountCreation | None = None,+ only_if_no_active_workspace: bool = False,+ ) -> CreatedWorkspace | None:+ """Run preparation after eligibility checks, holding any required owner lock through commit."""+ ...+++class WorkspaceProvisioningEffects(Protocol):+ def prepare(self, name: str) -> WorkspaceCreation: ...++ def bind_owner(self, workspace_id: str, account_id: str) -> None: ...++ def created(self, workspace: CreatedWorkspace, *, owner_id: str | None) -> None: ...++ def join_default_workspace(self, account_id: str) -> None: ...+++class WorkspaceMemberWriter(Protocol):+ def join_member(+ self,+ *,+ workspace_id: str,+ account_id: str,+ email: str,+ role: TenantAccountRole,+ operator_account_id: str | None,+ ) -> WorkspaceMembership: ...+++class WorkspaceProvisioningService:+ def __init__(+ self,+ *,+ owners: WorkspaceOwnerQuery,+ provisioning: WorkspaceProvisioningStore,+ effects: WorkspaceProvisioningEffects,+ policies: WorkspaceCreationPolicy,+ memberships: WorkspaceMembershipQuery,+ members: WorkspaceMemberWriter,+ ) -> None:+ self._owners = owners+ self._provisioning = provisioning+ self._effects = effects+ self._policies = policies+ self._memberships = memberships+ self._members = members++ def create(self, *, name: str, owner_email: str | None = None) -> CreatedWorkspace:+ owner_id = None+ if owner_email is not None:+ owner = self._owners.find_first_by_email(owner_email)+ if owner is None:+ raise WorkspaceOwnerNotFoundError()+ owner_id = owner.id+ if not self._policies.has_workspace_capacity():+ raise WorkspacesLimitExceededError()+ workspace = self._create(name=name, owner_id=owner_id)+ assert workspace is not None+ return workspace++ def create_owner_workspace(+ self, account_id: str, *, name: str | None = None, is_setup: bool = False, if_missing: bool = False+ ) -> None:+ if if_missing and self._memberships.list_ids_for_account(account_id):+ return+ if not is_setup and not self._policies.is_workspace_creation_allowed():+ raise WorkSpaceNotAllowedCreateError()+ if not self._policies.has_workspace_capacity():+ raise WorkspacesLimitExceededError()+ owner = self._owners.get(account_id)+ if owner is None:+ raise AccountNotFoundError()+ self._create(name=name or f"{owner.name}'s Workspace", owner_id=owner.id)++ def _create(+ self,+ *,+ name: str,+ owner_id: str | None,+ account: AccountCreation | None = None,+ only_if_no_active_workspace: bool = False,+ ) -> CreatedWorkspace | None:+ def prepare() -> WorkspaceCreation:+ creation = self._effects.prepare(name)+ if owner_id is not None:+ self._effects.bind_owner(creation.id, owner_id)+ return creation++ workspace = self._provisioning.provision(+ prepare,+ owner_id=owner_id,+ account=account,+ only_if_no_active_workspace=only_if_no_active_workspace,+ )+ if workspace is not None:+ self._effects.created(workspace, owner_id=owner_id)+ return workspace++ def create_with_owner_workspace(+ self,+ *,+ email: str,+ name: str,+ interface_language: str,+ timezone: str,+ ip_address: str,+ ) -> str:+ if self._owners.normalized_email_exists(email):+ raise AccountNormalizedEmailAlreadyInUseError+ account = AccountCreation(+ email=email,+ name=name,+ interface_language=interface_language,+ interface_theme="light",+ timezone=timezone,+ ip_address=ip_address,+ check_normalized_email=True,+ )+ self._create(name=f"{name}'s Workspace", owner_id=account.id, account=account)+ self._effects.join_default_workspace(account.id)+ return account.id++ def ensure_owner_workspace(self, account_id: str) -> None:+ owner = self._owners.get(account_id)+ if owner is None:+ raise AccountNotFoundError+ if self._memberships.has_active_for_account(account_id):+ return+ self._create(name=f"{owner.name}'s Workspace", owner_id=account_id, only_if_no_active_workspace=True)++ def join_member(+ self,+ *,+ workspace_id: str,+ account_id: str,+ email: str,+ role: str,+ operator_account_id: str | None,+ ) -> WorkspaceMembership:+ try:+ member_role = TenantAccountRole(role)+ except ValueError as exc:+ raise InvalidWorkspaceMemberRoleError("invalid workspace member role.") from exc+ if member_role == TenantAccountRole.OWNER:+ raise InvalidWorkspaceMemberRoleError("cannot join workspace as owner.")+ return self._members.join_member(+ workspace_id=workspace_id,+ account_id=account_id,+ email=email,+ role=member_role,+ operator_account_id=operator_account_id,+ )diff --git a/api/services/workspace/service.py b/api/services/workspace/service.pynew file mode 100644index 00000000000..fe4dd5a87af--- /dev/null+++ b/api/services/workspace/service.py@@ -0,0 +1,223 @@+"""Workspace management and listing use cases with application-owned ports."""++from collections.abc import Iterator, Mapping, Sequence+from typing import Protocol++from enums import CloudPlan+from machinery.context import RequestContext+from services.errors.file import UnsupportedFileTypeError+from services.errors.workspace import WorkspaceArchivedError, WorkspaceNotFoundError+from services.workspace.contracts import (+ EffectiveCreditPool,+ WorkspaceCustomConfig,+ WorkspaceCustomConfigChanges,+ WorkspaceFeatures,+ WorkspacePage,+ WorkspacePermission,+ WorkspaceRecord,+ WorkspaceSnapshot,+ WorkspaceSummary,+)+++class WorkspaceStore(Protocol):+ def get(self, workspace_id: str) -> WorkspaceSnapshot | None: ...++ def get_many(self, workspace_ids: Sequence[str]) -> tuple[WorkspaceSnapshot, ...]: ...++ def list_memberships(self, account_id: str) -> tuple[WorkspaceSnapshot, ...]: ...++ def find_membership(self, account_id: str, workspace_id: str) -> WorkspaceSnapshot | None: ...++ def list_member_ids(self, workspace_id: str, *, offset: int, limit: int) -> tuple[str, ...]: ...++ def list_all(self, *, page: int, limit: int) -> WorkspacePage: ...++ def get_for_account(self, workspace_id: str, account_id: str) -> WorkspaceSnapshot | None: ...++ def switch(self, *, account_id: str, workspace_id: str) -> WorkspaceSnapshot: ...++ def rename(self, *, workspace_id: str, account_id: str, name: str) -> WorkspaceSnapshot: ...++ def update_custom_config(+ self, *, workspace_id: str, account_id: str, changes: WorkspaceCustomConfig+ ) -> WorkspaceSnapshot: ...+++class WorkspaceFeatureGateway(Protocol):+ def get_features(self, workspace_id: str) -> WorkspaceFeatures: ...++ def get_effective_credit_pool(self, workspace_id: str) -> EffectiveCreditPool: ...++ def logo_url(self, workspace_id: str) -> str: ...++ def get_permission(self, workspace_id: str) -> WorkspacePermission: ...+++class WorkspaceLogoGateway(Protocol):+ def upload(self, context: RequestContext, *, filename: str, content: bytes, mimetype: str) -> str: ...+++class WorkspaceService:+ def __init__(+ self, *, workspaces: WorkspaceStore, features: WorkspaceFeatureGateway, logos: WorkspaceLogoGateway+ ) -> None:+ self._workspaces = workspaces+ self._features = features+ self._logos = logos++ def get(self, workspace_id: str) -> WorkspaceSnapshot | None:+ return self._workspaces.get(workspace_id)++ def get_many(self, workspace_ids: Sequence[str]) -> tuple[WorkspaceSnapshot, ...]:+ return self._workspaces.get_many(workspace_ids)++ def list_memberships(self, account_id: str) -> tuple[WorkspaceSnapshot, ...]:+ return self._workspaces.list_memberships(account_id)++ def find_membership(self, account_id: str, workspace_id: str) -> WorkspaceSnapshot | None:+ return self._workspaces.find_membership(account_id, workspace_id)++ def switch_membership(self, account_id: str, workspace_id: str) -> WorkspaceSnapshot:+ return self._workspaces.switch(account_id=account_id, workspace_id=workspace_id)++ def iter_member_account_id_batches(self, workspace_id: str, batch_size: int) -> Iterator[tuple[str, ...]]:+ if batch_size <= 0:+ raise ValueError("batch_size must be positive")+ offset = 0+ while account_ids := self._workspaces.list_member_ids(workspace_id, offset=offset, limit=batch_size):+ yield account_ids+ offset += len(account_ids)++ def list_all(self, *, page: int, limit: int) -> WorkspacePage:+ return self._workspaces.list_all(page=page, limit=limit)++ def _current(self, context: RequestContext) -> WorkspaceSnapshot:+ workspace = self._workspaces.get_for_account(context.active_workspace_id, context.account_id)+ if workspace is None:+ raise WorkspaceNotFoundError()+ return workspace++ def current_summary(self, context: RequestContext) -> dict[str, object]:+ workspace = self._current(context)+ if workspace.status == "archive":+ raise WorkspaceArchivedError()+ credits = self.get_effective_credit_pool(workspace.id)+ return {+ "id": workspace.id,+ "name": workspace.name,+ "role": workspace.role,+ "plan": credits.plan,+ "credits": credits.remaining_credits,+ }++ def get_effective_credit_pool(self, workspace_id: str) -> EffectiveCreditPool:+ return self._features.get_effective_credit_pool(workspace_id)++ def switch(self, context: RequestContext, workspace_id: str) -> dict[str, object]:+ workspace = self._workspaces.switch(account_id=context.account_id, workspace_id=workspace_id)+ return self._tenant_info(workspace)++ def custom_config(self, context: RequestContext) -> WorkspaceCustomConfig:+ return self._public_config(self._current(context))++ def update_custom_config(self, context: RequestContext, changes: WorkspaceCustomConfigChanges) -> dict[str, object]:+ current = self._current(context).custom_config+ config = WorkspaceCustomConfig(+ remove_webapp_brand=changes.remove_webapp_brand+ if changes.remove_webapp_brand is not None+ else current.remove_webapp_brand,+ replace_webapp_logo=changes.replace_webapp_logo+ if changes.replace_webapp_logo is not None+ else current.replace_webapp_logo,+ )+ workspace = self._workspaces.update_custom_config(+ workspace_id=context.active_workspace_id, account_id=context.account_id, changes=config+ )+ return self._tenant_info(workspace)++ def rename(self, context: RequestContext, name: str) -> dict[str, object]:+ workspace = self._workspaces.rename(+ workspace_id=context.active_workspace_id, account_id=context.account_id, name=name+ )+ return self._tenant_info(workspace)++ def upload_logo(self, context: RequestContext, *, filename: str, content: bytes, mimetype: str) -> str:+ if filename.split(".")[-1].lower() not in {"svg", "png"}:+ raise UnsupportedFileTypeError()+ return self._logos.upload(context, filename=filename, content=content, mimetype=mimetype)++ def permission(self, context: RequestContext) -> WorkspacePermission:+ return self._features.get_permission(context.active_workspace_id)++ def _public_config(self, workspace: WorkspaceSnapshot) -> WorkspaceCustomConfig:+ return WorkspaceCustomConfig(+ remove_webapp_brand=workspace.custom_config.remove_webapp_brand,+ replace_webapp_logo=self._features.logo_url(workspace.id)+ if workspace.custom_config.replace_webapp_logo+ else None,+ )++ def _tenant_info(self, workspace: WorkspaceSnapshot) -> dict[str, object]:+ # Repository writes have committed and closed before Feature/Billing I/O.+ features = self._features.get_features(workspace.id)+ credits = features.credits+ info: dict[str, object] = {+ "id": workspace.id,+ "name": workspace.name,+ "status": workspace.status,+ "created_at": workspace.created_at,+ "role": workspace.role,+ "plan": credits.plan,+ "trial_end_reason": None,+ }+ # Preserve the existing workspace-wide privileged-member check.+ if features.can_replace_logo and workspace.has_privileged_member:+ info["custom_config"] = self._public_config(workspace)+ if credits.plan is not None:+ info["next_credit_reset_date"] = credits.next_credit_reset_date+ if credits.quota_limit is not None:+ info["trial_credits"] = credits.quota_limit+ info["trial_credits_used"] = credits.quota_used+ if credits.exhausted_at is not None:+ info["trial_credits_exhausted_at"] = credits.exhausted_at+ return info+++class WorkspacePlanGateway(Protocol):+ def resolve_many(self, workspace_ids: Sequence[str]) -> Mapping[str, str]: ...+++class WorkspaceQuery(Protocol):+ def list_for_account(self, account_id: str) -> Sequence[WorkspaceRecord]: ...+++class WorkspaceQueryService:+ def __init__(+ self,+ *,+ workspaces: WorkspaceQuery,+ plans: WorkspacePlanGateway,+ ) -> None:+ self._workspaces = workspaces+ self._plans = plans++ def list_for_account(self, context: RequestContext) -> tuple[WorkspaceSummary, ...]:+ records = tuple(self._workspaces.list_for_account(context.account_id))++ # The repository closes its read Session before plan resolution+ # performs Billing/Feature I/O.+ plans = self._plans.resolve_many([record.id for record in records])++ return tuple(+ WorkspaceSummary(+ id=record.id,+ name=record.name,+ plan=plans.get(record.id, CloudPlan.SANDBOX),+ status=record.status,+ created_at=record.created_at,+ last_opened_at=record.last_opened_at,+ current=record.id == context.active_workspace_id,+ )+ for record in records+ )diff --git a/api/services/workspace_member_query_service.py b/api/services/workspace_member_query_service.pydeleted file mode 100644index b3570ef54d7..00000000000--- a/api/services/workspace_member_query_service.py+++ /dev/null@@ -1,94 +0,0 @@-"""Application service for listing members of the active Console workspace."""--from collections.abc import Mapping, Sequence-from datetime import datetime-from typing import NamedTuple, Protocol--from machinery.context import RequestContext---class WorkspaceMemberRole(NamedTuple):- id: str- name: str---class WorkspaceMemberRecord(NamedTuple):- id: str- name: str- email: str- avatar: str | None- last_login_at: datetime | None- last_active_at: datetime- created_at: datetime- status: str- legacy_role: str---class WorkspaceMemberQuery(Protocol):- def list_for_workspace(self, workspace_id: str) -> Sequence[WorkspaceMemberRecord]: ...---class WorkspaceMemberRoleSubject(NamedTuple):- account_id: str- legacy_role: str---class WorkspaceMemberRoleResolver(Protocol):- def resolve_many(- self,- workspace_id: str,- actor_account_id: str,- subjects: Sequence[WorkspaceMemberRoleSubject],- ) -> Mapping[str, Sequence[WorkspaceMemberRole]]: ...---class WorkspaceMemberSummary(NamedTuple):- id: str- name: str- email: str- avatar: str | None- last_login_at: datetime | None- last_active_at: datetime- created_at: datetime- role: str- roles: tuple[WorkspaceMemberRole, ...]- status: str---class WorkspaceMemberQueryService:- def __init__(- self,- *,- members: WorkspaceMemberQuery,- roles: WorkspaceMemberRoleResolver,- ) -> None:- self._members = members- self._roles = roles-- def list_current(self, context: RequestContext) -> tuple[WorkspaceMemberSummary, ...]:- workspace_id = context.active_workspace_id-- records = tuple(self._members.list_for_workspace(workspace_id))- role_subjects = tuple(- WorkspaceMemberRoleSubject(account_id=record.id, legacy_role=record.legacy_role) for record in records- )-- # The repository closes its read Session before role resolution- # performs enterprise I/O.- roles_by_member = self._roles.resolve_many(workspace_id, context.account_id, role_subjects)-- return tuple(- WorkspaceMemberSummary(- id=record.id,- name=record.name,- email=record.email,- avatar=record.avatar,- last_login_at=record.last_login_at,- last_active_at=record.last_active_at,- created_at=record.created_at,- role=record.legacy_role,- roles=tuple(roles_by_member.get(record.id, ())),- status=record.status,- )- for record in records- )diff --git a/api/services/workspace_member_role_resolver.py b/api/services/workspace_member_role_resolver.pydeleted file mode 100644index d2a4ceacec2..00000000000--- a/api/services/workspace_member_role_resolver.py+++ /dev/null@@ -1,43 +0,0 @@-"""Deployment-compatible role resolution for workspace-member queries."""--from collections.abc import Mapping, Sequence-from typing import override--from configs import dify_config-from services.enterprise import rbac_service as enterprise_rbac_service-from services.workspace_member_query_service import (- WorkspaceMemberRole,- WorkspaceMemberRoleResolver,- WorkspaceMemberRoleSubject,-)---class DeploymentWorkspaceMemberRoleResolver(WorkspaceMemberRoleResolver):- """Preserve deployment-specific legacy and enterprise role behavior."""-- @override- def resolve_many(- self,- workspace_id: str,- actor_account_id: str,- subjects: Sequence[WorkspaceMemberRoleSubject],- ) -> Mapping[str, Sequence[WorkspaceMemberRole]]:- role_subjects = tuple(subjects)- if not role_subjects:- return {}-- if not dify_config.RBAC_ENABLED:- return {- subject.account_id: (WorkspaceMemberRole(id=subject.legacy_role, name=subject.legacy_role),)- for subject in role_subjects- }-- member_roles = enterprise_rbac_service.RBACService.MemberRoles.batch_get(- workspace_id,- actor_account_id,- [subject.account_id for subject in role_subjects],- )- return {- item.account_id: tuple(WorkspaceMemberRole(id=role.id, name=role.name) for role in item.roles)- for item in member_roles- }diff --git a/api/services/workspace_plan_gateway.py b/api/services/workspace_plan_gateway.pydeleted file mode 100644index 22792b3e38a..00000000000--- a/api/services/workspace_plan_gateway.py+++ /dev/null@@ -1,44 +0,0 @@-"""Deployment-aware plan gateway for workspace queries."""--import logging-from collections.abc import Mapping, Sequence-from typing import override--from configs import dify_config-from enums import CloudPlan, DeploymentEdition-from services.billing_service import BillingService-from services.feature_service import FeatureService-from services.workspace_query_service import WorkspacePlanGateway--logger = logging.getLogger(__name__)---class DeploymentWorkspacePlanGateway(WorkspacePlanGateway):- """Resolve workspace plans using deployment-specific Billing and Feature sources."""-- @override- def resolve_many(self, workspace_ids: Sequence[str]) -> Mapping[str, str]:- ids = tuple(workspace_ids)- if not ids:- return {}-- is_enterprise_only = dify_config.DEPLOYMENT_EDITION == DeploymentEdition.ENTERPRISE- if is_enterprise_only:- return dict.fromkeys(ids, str(CloudPlan.SANDBOX))-- is_saas = dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD- bulk_plans = BillingService.get_plan_bulk(ids) if is_saas else {}- if is_saas and not bulk_plans:- logger.warning("get_plan_bulk returned empty result, falling back to FeatureService")-- resolved: dict[str, str] = {}- for workspace_id in ids:- tenant_plan = bulk_plans.get(workspace_id)- if tenant_plan:- resolved[workspace_id] = tenant_plan["plan"] or CloudPlan.SANDBOX- continue-- features = FeatureService.get_features(workspace_id, exclude_vector_space=True)- resolved[workspace_id] = features.billing.subscription.plan or CloudPlan.SANDBOX-- return resolveddiff --git a/api/services/workspace_query_service.py b/api/services/workspace_query_service.pydeleted file mode 100644index 746454da3c5..00000000000--- a/api/services/workspace_query_service.py+++ /dev/null@@ -1,65 +0,0 @@-"""Application service for listing workspaces visible to a Console account."""--from collections.abc import Mapping, Sequence-from datetime import datetime-from typing import NamedTuple, Protocol--from enums import CloudPlan-from machinery.context import RequestContext---class WorkspacePlanGateway(Protocol):- def resolve_many(self, workspace_ids: Sequence[str]) -> Mapping[str, str]: ...---class WorkspaceRecord(NamedTuple):- id: str- name: str | None- status: str- created_at: datetime- last_opened_at: datetime | None---class WorkspaceQuery(Protocol):- def list_for_account(self, account_id: str) -> Sequence[WorkspaceRecord]: ...---class WorkspaceSummary(NamedTuple):- id: str- name: str | None- plan: str- status: str- created_at: datetime- last_opened_at: datetime | None- current: bool---class WorkspaceQueryService:- def __init__(- self,- *,- workspaces: WorkspaceQuery,- plans: WorkspacePlanGateway,- ) -> None:- self._workspaces = workspaces- self._plans = plans-- def list_for_account(self, context: RequestContext) -> tuple[WorkspaceSummary, ...]:- records = tuple(self._workspaces.list_for_account(context.account_id))-- # The repository closes its read Session before plan resolution- # performs Billing/Feature I/O.- plans = self._plans.resolve_many([record.id for record in records])-- return tuple(- WorkspaceSummary(- id=record.id,- name=record.name,- plan=plans.get(record.id, CloudPlan.SANDBOX),- status=record.status,- created_at=record.created_at,- last_opened_at=record.last_opened_at,- current=record.id == context.active_workspace_id,- )- for record in records- )diff --git a/api/services/workspace_service.py b/api/services/workspace_service.pydeleted file mode 100644index 9cfd620867a..00000000000--- a/api/services/workspace_service.py+++ /dev/null@@ -1,190 +0,0 @@-from dataclasses import dataclass-from typing import Literal--from flask_login import current_user-from sqlalchemy import select-from sqlalchemy.orm import Session--from configs import dify_config-from enums import CloudPlan, DeploymentEdition-from models.account import Tenant, TenantAccountJoin, TenantAccountRole-from services.account_service import TenantService-from services.billing_service import BillingService-from services.feature_service import FeatureService---@dataclass(frozen=True)-class EffectiveCreditPool:- plan: CloudPlan | None = None- pool_type: Literal["paid", "trial"] | None = None- quota_limit: int | None = None- quota_used: int | None = None- exhausted_at: int | None = None- next_credit_reset_date: int | None = None-- @property- def remaining_credits(self) -> int | None:- if self.quota_limit is None or self.quota_used is None:- return None- if self.is_unlimited:- return -1- return max(0, self.quota_limit - self.quota_used)-- @property- def is_unlimited(self) -> bool:- return self.quota_limit == -1-- @property- def is_exhausted(self) -> bool:- remaining_credits = self.remaining_credits- return not self.is_unlimited and (remaining_credits is None or remaining_credits <= 0)---def _set_credit_pool_info(- tenant_info: dict[str, object], *, quota_limit: int, quota_used: int, exhausted_at: int | None = None-) -> None:- tenant_info["trial_credits"] = quota_limit- tenant_info["trial_credits_used"] = quota_used- if isinstance(exhausted_at, int) and exhausted_at > 0 and quota_limit > 0 and quota_used >= quota_limit:- tenant_info["trial_credits_exhausted_at"] = exhausted_at---class WorkspaceService:- @classmethod- def get_effective_credit_pool(cls, tenant_id: str, *, session: Session) -> EffectiveCreditPool:- if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:- return EffectiveCreditPool()-- billing_info = BillingService.get_info(tenant_id, exclude_vector_space=True)- subscription_plan = CloudPlan(billing_info["subscription"]["plan"])-- from services.credit_pool_service import CreditPoolBalance, CreditPoolService-- effective_pool = None- effective_pool_type: Literal["paid", "trial"] = "trial"- if subscription_plan != CloudPlan.SANDBOX:- paid_pool = CreditPoolService.get_pool(tenant_id=tenant_id, pool_type="paid", session=session)- if paid_pool is not None and (paid_pool.quota_limit == -1 or paid_pool.quota_limit > paid_pool.quota_used):- effective_pool = paid_pool- effective_pool_type = "paid"-- if effective_pool is None:- effective_pool = CreditPoolService.get_pool(tenant_id=tenant_id, pool_type="trial", session=session)-- if effective_pool is None:- return EffectiveCreditPool(- plan=subscription_plan,- next_credit_reset_date=billing_info.get("next_credit_reset_date"),- )-- exhausted_at = effective_pool.exhausted_at if isinstance(effective_pool, CreditPoolBalance) else None- if not (- isinstance(exhausted_at, int)- and exhausted_at > 0- and effective_pool.quota_limit > 0- and effective_pool.quota_used >= effective_pool.quota_limit- ):- exhausted_at = None-- return EffectiveCreditPool(- plan=subscription_plan,- pool_type=effective_pool_type,- quota_limit=effective_pool.quota_limit,- quota_used=effective_pool.quota_used,- exhausted_at=exhausted_at,- next_credit_reset_date=billing_info.get("next_credit_reset_date"),- )-- @classmethod- def get_current_workspace_summary(cls, tenant: Tenant, account_id: str, *, session: Session) -> dict[str, object]:- tenant_account_join = session.scalar(- select(TenantAccountJoin)- .where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == account_id)- .limit(1)- )- assert tenant_account_join is not None, "TenantAccountJoin not found"-- effective_pool = cls.get_effective_credit_pool(tenant.id, session=session)-- return {- "id": tenant.id,- "name": tenant.name,- "role": tenant_account_join.role,- "plan": effective_pool.plan,- "credits": effective_pool.remaining_credits,- }-- @classmethod- def get_tenant_info(cls, tenant: Tenant, session: Session):- if not tenant:- return None- tenant_info: dict[str, object] = {- "id": tenant.id,- "name": tenant.name,- "status": tenant.status,- "created_at": tenant.created_at,- "trial_end_reason": None,- "role": "normal",- }-- # Get role of user- tenant_account_join = session.scalar(- select(TenantAccountJoin)- .where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == current_user.id)- .limit(1)- )- assert tenant_account_join is not None, "TenantAccountJoin not found"- tenant_info["role"] = tenant_account_join.role-- feature = FeatureService.get_features(tenant.id, exclude_vector_space=True)- tenant_info["plan"] = (- feature.billing.subscription.plan if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD else None- )- can_replace_logo = feature.can_replace_logo-- if can_replace_logo and TenantService.has_roles(- tenant, [TenantAccountRole.OWNER, TenantAccountRole.ADMIN], session=session- ):- base_url = dify_config.FILES_URL- replace_webapp_logo = (- f"{base_url}/files/workspaces/{tenant.id}/webapp-logo"- if tenant.custom_config_dict.get("replace_webapp_logo")- else None- )- remove_webapp_brand = tenant.custom_config_dict.get("remove_webapp_brand", False)-- tenant_info["custom_config"] = {- "remove_webapp_brand": remove_webapp_brand,- "replace_webapp_logo": replace_webapp_logo,- }- if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:- tenant_info["next_credit_reset_date"] = feature.next_credit_reset_date-- from services.credit_pool_service import CreditPoolBalance, CreditPoolService-- paid_pool = CreditPoolService.get_pool(tenant_id=tenant.id, pool_type="paid", session=session)- # if the tenant is not on the sandbox plan and the paid pool is not full, use the paid pool- if (- feature.billing.subscription.plan != CloudPlan.SANDBOX- and paid_pool is not None- and (paid_pool.quota_limit == -1 or paid_pool.quota_limit > paid_pool.quota_used)- ):- exhausted_at = paid_pool.exhausted_at if isinstance(paid_pool, CreditPoolBalance) else None- _set_credit_pool_info(- tenant_info,- quota_limit=paid_pool.quota_limit,- quota_used=paid_pool.quota_used,- exhausted_at=exhausted_at,- )- else:- trial_pool = CreditPoolService.get_pool(tenant_id=tenant.id, pool_type="trial", session=session)- if trial_pool:- exhausted_at = trial_pool.exhausted_at if isinstance(trial_pool, CreditPoolBalance) else None- _set_credit_pool_info(- tenant_info,- quota_limit=trial_pool.quota_limit,- quota_used=trial_pool.quota_used,- exhausted_at=exhausted_at,- )-- return tenant_infodiff --git a/api/tasks/add_document_to_index_task.py b/api/tasks/add_document_to_index_task.pyindex 76486cb51e2..7010795e30b 100644--- a/api/tasks/add_document_to_index_task.py+++ b/api/tasks/add_document_to_index_task.py@@ -8,7 +8,7 @@ from sqlalchemy import delete, select, updatefrom core.db.session_factory import session_factoryfrom core.rag.index_processor.constant.doc_type import DocTypefrom core.rag.index_processor.constant.index_type import IndexStructureType-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom core.rag.models.document import AttachmentDocument, ChildDocument, Documentfrom extensions.ext_redis import redis_clientfrom libs.datetime_utils import naive_utc_nowdiff --git a/api/tasks/clean_dataset_task.py b/api/tasks/clean_dataset_task.pyindex 5bf8784e3c2..5a4baabefbc 100644--- a/api/tasks/clean_dataset_task.py+++ b/api/tasks/clean_dataset_task.py@@ -6,7 +6,7 @@ from celery import shared_taskfrom sqlalchemy import delete, selectfrom core.db.session_factory import session_factory-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom core.tools.utils.web_reader_tool import get_image_upload_file_idsfrom extensions.ext_storage import storagefrom models import WorkflowTypediff --git a/api/tasks/create_segment_to_index_task.py b/api/tasks/create_segment_to_index_task.pyindex eef7d0d2d50..c329c7a4aa4 100644--- a/api/tasks/create_segment_to_index_task.py+++ b/api/tasks/create_segment_to_index_task.py@@ -6,7 +6,7 @@ from celery import shared_taskfrom sqlalchemy import select, updatefrom core.db.session_factory import session_factory-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom core.rag.models.document import Documentfrom extensions.ext_redis import redis_clientfrom libs.datetime_utils import naive_utc_nowdiff --git a/api/tasks/deal_dataset_index_update_task.py b/api/tasks/deal_dataset_index_update_task.pyindex 02eae8ab6cf..c448e9be48a 100644--- a/api/tasks/deal_dataset_index_update_task.py+++ b/api/tasks/deal_dataset_index_update_task.py@@ -8,7 +8,7 @@ from sqlalchemy import select, updatefrom core.db.session_factory import session_factoryfrom core.rag.index_processor.constant.doc_type import DocTypefrom core.rag.index_processor.constant.index_type import IndexStructureType-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom core.rag.models.document import AttachmentDocument, ChildDocument, Documentfrom models.dataset import Dataset, DocumentSegmentfrom models.dataset import Document as DatasetDocumentdiff --git a/api/tasks/deal_dataset_vector_index_task.py b/api/tasks/deal_dataset_vector_index_task.pyindex 4cb8ac6b84c..46527bb46fe 100644--- a/api/tasks/deal_dataset_vector_index_task.py+++ b/api/tasks/deal_dataset_vector_index_task.py@@ -8,7 +8,7 @@ from sqlalchemy import select, updatefrom core.db.session_factory import session_factoryfrom core.rag.index_processor.constant.doc_type import DocTypefrom core.rag.index_processor.constant.index_type import IndexStructureType-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom core.rag.models.document import AttachmentDocument, ChildDocument, Documentfrom models.dataset import Dataset, DocumentSegmentfrom models.dataset import Document as DatasetDocumentdiff --git a/api/tasks/delete_segment_from_index_task.py b/api/tasks/delete_segment_from_index_task.pyindex df29e9e98af..32940c63937 100644--- a/api/tasks/delete_segment_from_index_task.py+++ b/api/tasks/delete_segment_from_index_task.py@@ -6,7 +6,7 @@ from celery import shared_taskfrom sqlalchemy import delete, selectfrom core.db.session_factory import session_factory-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom extensions.ext_storage import storagefrom models.dataset import Dataset, Document, SegmentAttachmentBindingfrom models.model import UploadFilediff --git a/api/tasks/disable_segment_from_index_task.py b/api/tasks/disable_segment_from_index_task.pyindex 75c52b7d9f4..6d7ceec862d 100644--- a/api/tasks/disable_segment_from_index_task.py+++ b/api/tasks/disable_segment_from_index_task.py@@ -6,7 +6,7 @@ from celery import shared_taskfrom sqlalchemy import selectfrom core.db.session_factory import session_factory-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom extensions.ext_redis import redis_clientfrom models.dataset import DocumentSegmentfrom models.enums import SegmentStatusdiff --git a/api/tasks/disable_segments_from_index_task.py b/api/tasks/disable_segments_from_index_task.pyindex c6e5aa76db5..4e9289c7520 100644--- a/api/tasks/disable_segments_from_index_task.py+++ b/api/tasks/disable_segments_from_index_task.py@@ -6,7 +6,7 @@ from celery import shared_taskfrom sqlalchemy import select, updatefrom core.db.session_factory import session_factory-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom extensions.ext_redis import redis_clientfrom models.dataset import Dataset, DocumentSegment, SegmentAttachmentBindingfrom models.dataset import Document as DatasetDocumentdiff --git a/api/tasks/document_indexing_sync_task.py b/api/tasks/document_indexing_sync_task.pyindex f0e46c25bdf..d77b3f1e39e 100644--- a/api/tasks/document_indexing_sync_task.py+++ b/api/tasks/document_indexing_sync_task.py@@ -8,7 +8,7 @@ from sqlalchemy import delete, selectfrom core.db.session_factory import get_session_maker, session_factoryfrom core.rag.extractor.notion_extractor import NotionExtractor-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom extensions.application_services.data_sources import build_data_source_credentialsfrom libs.datetime_utils import naive_utc_nowfrom models.dataset import Dataset, Document, DocumentSegmentdiff --git a/api/tasks/document_indexing_update_task.py b/api/tasks/document_indexing_update_task.pyindex 73929fd54d0..2304529a243 100644--- a/api/tasks/document_indexing_update_task.py+++ b/api/tasks/document_indexing_update_task.py@@ -7,7 +7,7 @@ from sqlalchemy import delete, selectfrom core.db.session_factory import session_factoryfrom core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom extensions.ext_storage import storagefrom libs.datetime_utils import naive_utc_nowfrom models.dataset import Dataset, Document, DocumentSegment, SegmentAttachmentBindingdiff --git a/api/tasks/duplicate_document_indexing_task.py b/api/tasks/duplicate_document_indexing_task.pyindex 5afa6582811..3f649980b02 100644--- a/api/tasks/duplicate_document_indexing_task.py+++ b/api/tasks/duplicate_document_indexing_task.py@@ -9,7 +9,7 @@ from sqlalchemy import delete, selectfrom configs import dify_configfrom core.db.session_factory import session_factoryfrom core.entities.document_task import DocumentTask-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom core.rag.pipeline.queue import TenantIsolatedTaskQueuefrom enums import CloudPlan, DeploymentEditionfrom libs.datetime_utils import naive_utc_nowdiff --git a/api/tasks/enable_segment_to_index_task.py b/api/tasks/enable_segment_to_index_task.pyindex f4075b9df86..71aaa107ba6 100644--- a/api/tasks/enable_segment_to_index_task.py+++ b/api/tasks/enable_segment_to_index_task.py@@ -8,7 +8,7 @@ from sqlalchemy import selectfrom core.db.session_factory import session_factoryfrom core.rag.index_processor.constant.doc_type import DocTypefrom core.rag.index_processor.constant.index_type import IndexStructureType-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom core.rag.models.document import AttachmentDocument, ChildDocument, Documentfrom extensions.ext_redis import redis_clientfrom libs.datetime_utils import naive_utc_nowdiff --git a/api/tasks/enable_segments_to_index_task.py b/api/tasks/enable_segments_to_index_task.pyindex 6a95d564728..044fe91b8f1 100644--- a/api/tasks/enable_segments_to_index_task.py+++ b/api/tasks/enable_segments_to_index_task.py@@ -8,7 +8,7 @@ from sqlalchemy import select, updatefrom core.db.session_factory import session_factoryfrom core.rag.index_processor.constant.doc_type import DocTypefrom core.rag.index_processor.constant.index_type import IndexStructureType-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom core.rag.models.document import AttachmentDocument, ChildDocument, Documentfrom extensions.ext_redis import redis_clientfrom libs.datetime_utils import naive_utc_nowdiff --git a/api/tasks/initialize_created_app_rbac_access_task.py b/api/tasks/initialize_created_app_rbac_access_task.pyindex ce1bfaea220..2a51e576699 100644--- a/api/tasks/initialize_created_app_rbac_access_task.py+++ b/api/tasks/initialize_created_app_rbac_access_task.py@@ -10,7 +10,6 @@ from sqlalchemy import selectfrom configs import dify_configfrom extensions.ext_database import dbfrom models import Agent, App, Dataset, TenantAccountJoin, TenantAccountRole-from services.account_service import TenantServicefrom services.enterprise import rbac_service as enterprise_rbac_servicelogger = logging.getLogger(__name__)@@ -191,11 +190,12 @@ def initialize_created_app_rbac_access_task(})+ from extensions.ext_application_services import application_services+try:- for account_ids in TenantService.iter_member_account_id_batches(+ for account_ids in application_services().workspaces.management.iter_member_account_id_batches(tenant_id,APP_RBAC_ACCOUNT_POLICY_BATCH_SIZE,- session=db.session(),):kind.replace_user_access_policies(tenant_id,@@ -203,7 +203,7 @@ def initialize_created_app_rbac_access_task(resource_id,enterprise_rbac_service.ReplaceUserAccessPolicies(access_policy_ids=[APP_RBAC_DEFAULT_ACCESS_POLICY_ID],- account_ids=account_ids,+ account_ids=list(account_ids),),)except Exception as exc:diff --git a/api/tasks/remove_document_from_index_task.py b/api/tasks/remove_document_from_index_task.pyindex de50e196e8e..55e10f907c2 100644--- a/api/tasks/remove_document_from_index_task.py+++ b/api/tasks/remove_document_from_index_task.py@@ -6,7 +6,7 @@ from celery import shared_taskfrom sqlalchemy import select, updatefrom core.db.session_factory import session_factory-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom extensions.ext_redis import redis_clientfrom libs.datetime_utils import naive_utc_nowfrom models.dataset import Document, DocumentSegmentdiff --git a/api/tasks/retry_document_indexing_task.py b/api/tasks/retry_document_indexing_task.pyindex 744723eae44..13d4e72e1ea 100644--- a/api/tasks/retry_document_indexing_task.py+++ b/api/tasks/retry_document_indexing_task.py@@ -8,7 +8,7 @@ from sqlalchemy import delete, selectfrom configs import dify_configfrom core.app.apps.pipeline.pipeline_generator import PipelineGeneratorfrom core.db.session_factory import get_session_maker, session_factory-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom enums import DeploymentEditionfrom extensions.application_services.data_sources import build_data_source_credentialsfrom extensions.ext_redis import redis_clientdiff --git a/api/tasks/sync_website_document_indexing_task.py b/api/tasks/sync_website_document_indexing_task.pyindex 30dc205b44c..34b892cc2cf 100644--- a/api/tasks/sync_website_document_indexing_task.py+++ b/api/tasks/sync_website_document_indexing_task.py@@ -7,7 +7,7 @@ from sqlalchemy import delete, selectfrom configs import dify_configfrom core.db.session_factory import session_factory-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom enums import DeploymentEditionfrom extensions.ext_redis import redis_clientfrom libs.datetime_utils import naive_utc_nowdiff --git a/api/tests/integration_tests/conftest.py b/api/tests/integration_tests/conftest.pyindex 25ee1974e92..1e5722acbc3 100644--- a/api/tests/integration_tests/conftest.py+++ b/api/tests/integration_tests/conftest.py@@ -13,9 +13,10 @@ from sqlalchemy.orm import Sessionfrom app_factory import create_appfrom configs.app_config import DifyConfig+from extensions.ext_application_services import application_servicesfrom extensions.ext_database import dbfrom models import Account, DifySetup, Tenant, TenantAccountJoin-from services.account_service import AccountService, RegisterService+from services.account.contracts import SetupInput_DEFUALT_TEST_ENV = ".env"_DEFAULT_VDB_TEST_ENV = "vdb.env"@@ -78,13 +79,15 @@ def setup_account(request) -> Generator[Account, None, None]:rand_suffix = random.randint(int(1e6), int(1e7)) # noqaname = f"test-user-{rand_suffix}"email = f"{name}@example.com"- RegisterService.setup(- email=email,- name=name,- password=secrets.token_hex(16),- ip_address="localhost",- language="en-US",- session=db.session(),+ application_services().setup.initialize(+ SetupInput(+ email=email,+ name=name,+ password=secrets.token_hex(16),+ ip_address="localhost",+ language="en-US",+ ),+ initialization_validated=True,)with _CACHED_APP.test_request_context():@@ -109,7 +112,7 @@ def flask_req_ctx():@pytest.fixturedef auth_header(setup_account) -> dict[str, str]:- token = AccountService.get_account_jwt_token(setup_account)+ token = application_services().accounts.lifecycle.login(setup_account.id, ip_address="127.0.0.1").access_tokenreturn {"Authorization": f"Bearer {token}"}diff --git a/api/tests/integration_tests/controllers/console/app/test_model_config_permissions.py b/api/tests/integration_tests/controllers/console/app/test_model_config_permissions.pyindex 8de1026374d..8d215e544e8 100644--- a/api/tests/integration_tests/controllers/console/app/test_model_config_permissions.py+++ b/api/tests/integration_tests/controllers/console/app/test_model_config_permissions.py@@ -87,11 +87,11 @@ class TestModelConfigResourcePermissions:# Mock current usermonkeypatch.setattr(model_config_api, "current_user", mock_account)- # Mock AccountService.load_user to prevent authentication issues- from services.account_service import AccountService+ # Mock AccountIdentityGateway.load_user to prevent authentication issues+ from services.account.adapters import AccountIdentityGatewaymock_load_user = mock.Mock(return_value=mock_account)- monkeypatch.setattr(AccountService, "load_user", mock_load_user)+ monkeypatch.setattr(AccountIdentityGateway, "load_user", mock_load_user)mock_validate_config = mock.Mock(return_value={diff --git a/api/tests/test_containers_integration_tests/.ruff.toml b/api/tests/test_containers_integration_tests/.ruff.tomlindex 4124d24b082..5a63b0df947 100644--- a/api/tests/test_containers_integration_tests/.ruff.toml+++ b/api/tests/test_containers_integration_tests/.ruff.toml@@ -23,7 +23,6 @@ extend-select = ["ANN401", "ARG"]"services/dataset_collection_binding.py" = ["ARG002"]"services/document_service_status.py" = ["ARG002"]"services/rag_pipeline/test_rag_pipeline_service_db.py" = ["ARG002"]-"services/test_account_service.py" = ["ARG002"]"services/test_advanced_prompt_template_service.py" = ["ARG002"]"services/test_app_dsl_service.py" = ["ANN401", "ARG001", "ARG002", "ARG005", "TID251"]"services/test_app_service.py" = ["ARG002"]@@ -46,7 +45,6 @@ extend-select = ["ANN401", "ARG"]"services/test_workflow_draft_variable_service.py" = ["ARG002"]"services/test_workflow_run_service.py" = ["ARG002"]"services/test_workflow_service.py" = ["ARG002"]-"services/test_workspace_service.py" = ["ARG002"]"services/tools/test_api_tools_manage_service.py" = ["ARG002"]"services/tools/test_mcp_tools_manage_service.py" = ["ARG002", "ARG005"]"services/tools/test_tools_transform_service.py" = ["ARG002"]diff --git a/api/tests/test_containers_integration_tests/controllers/console/app/test_chat_conversation_status_count_api.py b/api/tests/test_containers_integration_tests/controllers/console/app/test_chat_conversation_status_count_api.pyindex 3e1477dacc9..f3e2c4c7249 100644--- a/api/tests/test_containers_integration_tests/controllers/console/app/test_chat_conversation_status_count_api.py+++ b/api/tests/test_containers_integration_tests/controllers/console/app/test_chat_conversation_status_count_api.py@@ -7,6 +7,7 @@ from flask.testing import FlaskClientfrom sqlalchemy.orm import Sessionfrom constants import HEADER_NAME_CSRF_TOKEN+from extensions.ext_application_services import application_servicesfrom graphon.enums import WorkflowExecutionStatusfrom libs.datetime_utils import naive_utc_nowfrom libs.token import _real_cookie_name, generate_csrf_token@@ -15,7 +16,6 @@ from models.account import AccountStatus, TenantAccountRole, TenantStatusfrom models.enums import ConversationFromSource, CreatorUserRolefrom models.model import App, AppMode, Conversation, Messagefrom models.workflow import WorkflowRun-from services.account_service import AccountServicefrom tests.test_containers_integration_tests.controllers.console.helpers import ensure_dify_setup@@ -143,7 +143,7 @@ def test_chat_conversation_status_count_includes_paused(workflow_run = _create_workflow_run(db_session_with_containers, app.id, tenant.id, account.id)_create_message(db_session_with_containers, app.id, conversation.id, workflow_run.id, account.id)- access_token = AccountService.get_account_jwt_token(account)+ access_token = application_services().accounts.lifecycle.login(account.id, ip_address="127.0.0.1").access_tokencsrf_token = generate_csrf_token(account.id)cookie_name = _real_cookie_name("csrf_token")diff --git a/api/tests/test_containers_integration_tests/controllers/console/datasets/test_data_source.py b/api/tests/test_containers_integration_tests/controllers/console/datasets/test_data_source.pyindex 1a9389d299b..fcd34cb6d6d 100644--- a/api/tests/test_containers_integration_tests/controllers/console/datasets/test_data_source.py+++ b/api/tests/test_containers_integration_tests/controllers/console/datasets/test_data_source.py@@ -15,7 +15,7 @@ from models.dataset import Dataset, Documentfrom models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatusfrom repositories.knowledge.dataset_repository import SQLAlchemyDatasetRepositoryfrom repositories.knowledge.document_repository import SQLAlchemyDocumentRepository-from repositories.workspace_member_query_repository import WorkspaceMemberQueryRepository+from repositories.workspace.workspace_repository import WorkspaceRepositoryfrom services.data_source.credential_gateway import ActorDatasourceCredentialResolverfrom services.data_source.notion_import_adapters import PluginNotionSourceGatewayfrom services.data_source.notion_import_application_service import NotionImportApplicationService@@ -94,7 +94,7 @@ def test_notion_page_is_marked_bound_from_persisted_document(notion_imports = NotionImportApplicationService(dataset_access=DatasetAccessService(datasets=datasets,- workspace_roles=WorkspaceMemberQueryRepository(session_factory=sessions),+ workspace_roles=WorkspaceRepository(session_factory=sessions),legacy_permissions_enabled=True,),datasets=datasets,diff --git a/api/tests/test_containers_integration_tests/controllers/console/helpers.py b/api/tests/test_containers_integration_tests/controllers/console/helpers.pyindex 7854de54fac..4cffa29a380 100644--- a/api/tests/test_containers_integration_tests/controllers/console/helpers.py+++ b/api/tests/test_containers_integration_tests/controllers/console/helpers.py@@ -10,12 +10,12 @@ from sqlalchemy.orm import Sessionfrom configs import dify_configfrom constants import HEADER_NAME_CSRF_TOKEN+from extensions.ext_application_services import application_servicesfrom libs.datetime_utils import naive_utc_nowfrom libs.token import _real_cookie_name, generate_csrf_tokenfrom models import Account, DifySetup, Tenant, TenantAccountJoinfrom models.account import AccountStatus, TenantAccountRole, TenantStatusfrom models.model import App, AppMode-from services.account_service import AccountServicedef ensure_dify_setup(db_session: Session) -> None:@@ -78,7 +78,7 @@ def create_console_app(db_session: Session, tenant_id: str, account_id: str, moddef authenticate_console_client(test_client: FlaskClient, account: Account) -> dict[str, str]:"""Attach console auth cookies/headers for endpoints guarded by login_required."""- access_token = AccountService.get_account_jwt_token(account)+ access_token = application_services().accounts.lifecycle.login(account.id, ip_address="127.0.0.1").access_tokencsrf_token = generate_csrf_token(account.id)test_client.set_cookie(_real_cookie_name("csrf_token"), csrf_token, domain="localhost")return {diff --git a/api/tests/test_containers_integration_tests/controllers/console/test_setup.py b/api/tests/test_containers_integration_tests/controllers/console/test_setup.pyindex cee425469e1..a38c1becd6f 100644--- a/api/tests/test_containers_integration_tests/controllers/console/test_setup.py+++ b/api/tests/test_containers_integration_tests/controllers/console/test_setup.py@@ -13,7 +13,8 @@ from sqlalchemy.orm import Sessionfrom models.account import Account, Tenant, TenantAccountJoinfrom models.model import DifySetup-from services.account_service import RegisterService+from services.account.contracts import SetupInput+from services.account.service import AccountSetupProvisionerfrom services.setup_adapters import RedisSetupLockfrom tests.test_containers_integration_tests.helpers import generate_valid_password@@ -21,9 +22,9 @@ from tests.test_containers_integration_tests.helpers import generate_valid_passw@pytest.fixturedef setup_dependencies() -> Iterator[MagicMock]:with (- patch("services.account_service.SystemFeatureService") as feature_service,- patch("services.account_service.BillingService") as billing_service,- patch("services.account_service.CommunityTelemetryService.report_install") as report_install,+ patch("services.account.login_adapters.SystemFeatureService") as feature_service,+ patch("services.account.login_adapters.BillingService") as billing_service,+ patch("services.account.adapters.CommunityTelemetryService.report_install") as report_install,):feature_service.is_registration_allowed.return_value = Truefeature_service.get_license.return_value.seats.is_available.return_value = True@@ -93,29 +94,14 @@ def test_concurrent_setup_requests_create_only_one_bootstrap_identity(second_lock_attempted = Event()attempt_guard = Lock()lock_attempts = 0- original_setup = RegisterService.setup+ original_setup = AccountSetupProvisioner.provisionoriginal_acquire = RedisSetupLock.acquire- def blocking_setup(- email: str,- name: str,- password: str,- ip_address: str,- language: str | None,- *,- session: Session,- ) -> None:+ def blocking_setup(self: AccountSetupProvisioner, setup: SetupInput) -> None:if not provision_started.is_set():provision_started.set()assert allow_provision_to_finish.wait(timeout=10)- original_setup(- email=email,- name=name,- password=password,- ip_address=ip_address,- language=language,- session=session,- )+ original_setup(self, setup)def tracked_acquire(self: RedisSetupLock) -> AbstractContextManager[None]:nonlocal lock_attempts@@ -134,7 +120,7 @@ def test_concurrent_setup_requests_create_only_one_bootstrap_identity(return response.status_codewith (- patch.object(RegisterService, "setup", side_effect=blocking_setup),+ patch.object(AccountSetupProvisioner, "provision", blocking_setup),patch.object(RedisSetupLock, "acquire", tracked_acquire),ThreadPoolExecutor(max_workers=2) as executor,):diff --git a/api/tests/test_containers_integration_tests/controllers/console/workspace/test_members.py b/api/tests/test_containers_integration_tests/controllers/console/workspace/test_members.pyindex 6829fc4e567..137fcbfa8b1 100644--- a/api/tests/test_containers_integration_tests/controllers/console/workspace/test_members.py+++ b/api/tests/test_containers_integration_tests/controllers/console/workspace/test_members.py@@ -11,11 +11,15 @@ from flask import Flaskfrom sqlalchemy.orm import Sessionfrom werkzeug.exceptions import HTTPException-import services+import services.errors.base+import services.errors.workspacefrom controllers.console.auth.error import MemberNotInTenantError-from controllers.console.workspace import members as members_modulefrom controllers.console.workspace.members import MemberCancelInviteApi, MemberUpdateRoleApi, OwnerTransfer+from extensions.ext_application_services import application_services+from libs.helper import TokenManager+from machinery.context import RequestContextfrom models.account import Account, Tenant, TenantAccountJoin, TenantAccountRole, TenantStatus+from services.workspace import gatewaysJsonResponse = dict[str, object]StatusResponse = tuple[JsonResponse, int]@@ -95,11 +99,8 @@ class WorkspaceMembersIntegrationFactory:@staticmethoddef create_owner_transfer_token(account: Account) -> str:- _, token = members_module.AccountService.generate_owner_transfer_token(- account.email,- account=account,- code="123456",- additional_data={},+ token = TokenManager.generate_token(+ account_id=account.id, email=account.email, token_type="owner_transfer", additional_data={"code": "123456"})return token@@ -126,17 +127,17 @@ class TestMemberCancelInviteApiWithContainers:with (flask_app_with_containers.test_request_context("/"),- patch.object(members_module.TenantService, "remove_member_from_tenant") as mock_remove_member,+ patch.object(application_services().workspaces.members, "remove") as mock_remove_member,):- result, status = method(api, current_user, member.id)+ result, status = method(api, RequestContext("request", None, current_user.id, tenant.id), member.id)assert status == 200assert result["result"] == "success"mock_remove_member.assert_called_once()called_tenant, called_member, called_current_user = mock_remove_member.call_args.args- assert called_tenant.id == tenant.id- assert called_member.id == member.id- assert called_current_user.id == current_user.id+ assert called_tenant == tenant.id+ assert called_member == member.id+ assert called_current_user == current_user.iddef test_cancel_not_found(self, flask_app_with_containers: Flask, db_session_with_containers: Session) -> None:api = MemberCancelInviteApi()@@ -146,7 +147,7 @@ class TestMemberCancelInviteApiWithContainers:with flask_app_with_containers.test_request_context("/"):with pytest.raises(HTTPException):- method(api, current_user, str(uuid4()))+ method(api, RequestContext("request", None, current_user.id, tenant.id), str(uuid4()))def test_cancel_cannot_operate_self(self, flask_app_with_containers: Flask, db_session_with_containers: Session@@ -160,12 +161,12 @@ class TestMemberCancelInviteApiWithContainers:with (flask_app_with_containers.test_request_context("/"),patch.object(- members_module.TenantService,- "remove_member_from_tenant",- side_effect=services.errors.account.CannotOperateSelfError("x"),+ application_services().workspaces.members,+ "remove",+ side_effect=services.errors.workspace.CannotOperateSelfError("x"),),):- result, status = method(api, current_user, member.id)+ result, status = method(api, RequestContext("request", None, current_user.id, tenant.id), member.id)assert status == 400assert result["code"] == "cannot-operate-self"@@ -180,12 +181,12 @@ class TestMemberCancelInviteApiWithContainers:with (flask_app_with_containers.test_request_context("/"),patch.object(- members_module.TenantService,- "remove_member_from_tenant",- side_effect=services.errors.account.NoPermissionError("x"),+ application_services().workspaces.members,+ "remove",+ side_effect=services.errors.base.NoPermissionError("x"),),):- result, status = method(api, current_user, member.id)+ result, status = method(api, RequestContext("request", None, current_user.id, tenant.id), member.id)assert status == 403assert result["code"] == "forbidden"@@ -202,12 +203,12 @@ class TestMemberCancelInviteApiWithContainers:with (flask_app_with_containers.test_request_context("/"),patch.object(- members_module.TenantService,- "remove_member_from_tenant",- side_effect=services.errors.account.MemberNotInTenantError(),+ application_services().workspaces.members,+ "remove",+ side_effect=services.errors.workspace.MemberNotInTenantError(),),):- result, status = method(api, current_user, member.id)+ result, status = method(api, RequestContext("request", None, current_user.id, tenant.id), member.id)assert status == 404assert result["code"] == "member-not-found"@@ -227,7 +228,7 @@ class TestMemberUpdateRoleApiWithContainers:)with flask_app_with_containers.test_request_context("/", json={"role": "normal"}):- result = method(api, current_user, member.id)+ result = method(api, RequestContext("request", None, current_user.id, tenant.id), member.id)if isinstance(result, tuple):result = result[0]@@ -247,7 +248,7 @@ class TestMemberUpdateRoleApiWithContainers:with flask_app_with_containers.test_request_context("/", json={"role": "normal"}):with pytest.raises(HTTPException):- method(api, current_user, str(uuid4()))+ method(api, RequestContext("request", None, current_user.id, tenant.id), str(uuid4()))class TestOwnerTransferApiWithContainers:@@ -261,7 +262,7 @@ class TestOwnerTransferApiWithContainers:with flask_app_with_containers.test_request_context("/", json={"token": token}):with pytest.raises(MemberNotInTenantError):- method(api, current_user, member.id)+ method(api, RequestContext("test", None, current_user.id, tenant.id), member.id)def test_member_not_found(self, flask_app_with_containers: Flask, db_session_with_containers: Session) -> None:api = OwnerTransfer()@@ -272,7 +273,7 @@ class TestOwnerTransferApiWithContainers:with flask_app_with_containers.test_request_context("/", json={"token": token}):with pytest.raises(HTTPException):- method(api, current_user, str(uuid4()))+ method(api, RequestContext("test", None, current_user.id, tenant.id), str(uuid4()))def test_transfer_success(self, flask_app_with_containers: Flask, db_session_with_containers: Session) -> None:api = OwnerTransfer()@@ -289,10 +290,10 @@ class TestOwnerTransferApiWithContainers:with (flask_app_with_containers.test_request_context("/", json={"token": token}),- patch.object(members_module.AccountService, "send_new_owner_transfer_notify_email") as mock_new_owner_email,- patch.object(members_module.AccountService, "send_old_owner_transfer_notify_email") as mock_old_owner_email,+ patch.object(gateways.send_new_owner_transfer_notify_email_task, "delay") as notify_new,+ patch.object(gateways.send_old_owner_transfer_notify_email_task, "delay") as notify_old,):- result = method(api, current_user, member.id)+ result = method(api, RequestContext("test", None, current_user.id, tenant.id), member.id)assert result["result"] == "success"assert (@@ -302,5 +303,7 @@ class TestOwnerTransferApiWithContainers:factory.get_join(db_session_with_containers, tenant=tenant, account=current_user).role== TenantAccountRole.NORMAL)- mock_new_owner_email.assert_called_once()- mock_old_owner_email.assert_called_once()+ notify_new.assert_called_once_with(language="en-US", to=member.email, workspace=tenant.name)+ notify_old.assert_called_once_with(+ language="en-US", to=current_user.email, workspace=tenant.name, new_owner_email=member.email+ )diff --git a/api/tests/test_containers_integration_tests/controllers/openapi/conftest.py b/api/tests/test_containers_integration_tests/controllers/openapi/conftest.pyindex 69bf01341c6..f05a5f5ce39 100644--- a/api/tests/test_containers_integration_tests/controllers/openapi/conftest.py+++ b/api/tests/test_containers_integration_tests/controllers/openapi/conftest.py@@ -1,7 +1,7 @@from __future__ import annotationsimport uuid-from collections.abc import Callable+from collections.abc import Callable, Sequencefrom unittest.mock import patchimport pytest@@ -12,11 +12,11 @@ from sqlalchemy.orm import Sessionfrom constants.oauth_bearer import TokenTypefrom controllers.openapi.auth.context import Contextfrom controllers.openapi.auth.loaders import PathParam, load_app-from controllers.openapi.auth.requirements import ResolveCaller+from controllers.openapi.auth.requirements import Requirement, ResolveCallerfrom controllers.openapi.auth.subjects import subject_from_authfrom libs.oauth_bearer import AuthContextfrom models import Account, Tenant-from services.account_service import AccountService, TenantService+from tests.test_containers_integration_tests.helpers import accounts as account_fixturesfrom tests.test_containers_integration_tests.helpers import generate_valid_password_CLIENT_ID = "integration-cli"@@ -37,14 +37,14 @@ def make_account(db_session_with_containers: Session) -> Callable[..., Account]:"""# Depend on db_session_with_containers so the app context / DB session is- # active for the real AccountService/TenantService calls below.+ # active for the composed account and workspace services below.assert db_session_with_containers is not Nonedef _make(*, with_owner_tenant: bool = True) -> Account:fake = Faker()- with patch("services.account_service.SystemFeatureService") as mock_feature_service:+ with patch("services.account.login_adapters.SystemFeatureService") as mock_feature_service:mock_feature_service.is_registration_allowed.return_value = True- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",@@ -52,7 +52,7 @@ def make_account(db_session_with_containers: Session) -> Callable[..., Account]:session=db_session_with_containers,)if with_owner_tenant:- TenantService.create_owner_tenant_if_not_exist(+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)return account@@ -64,10 +64,10 @@ def add_tenant_for_account(account: Account, *, session: Session, role: str = "normal", name: str = "Second WS") -> Tenant:"""Create an additional tenant and join ``account`` to it (real service calls)."""- with patch("services.account_service.SystemFeatureService") as mock_feature_service:+ with patch("services.account.login_adapters.SystemFeatureService") as mock_feature_service:mock_feature_service.is_workspace_creation_allowed.return_value = True- tenant = TenantService.create_tenant(name=name, session=session)- TenantService.create_tenant_member(tenant, account, session, role=role)+ tenant = account_fixtures.create_workspace(name=name, session=session)+ account_fixtures.join_workspace(tenant, account, session, role=role)return tenant@@ -95,6 +95,7 @@ def context_for(session: Session,view_args: dict[str, str] | None = None,token_id: uuid.UUID | None = None,+ requirements: Sequence[Requirement] = (),) -> Context:"""Build the ``Context`` a handler is given after the pipeline ran.@@ -105,17 +106,16 @@ def context_for(``token_id`` only matters to the ``/account/sessions*`` family, which readsit back off the subject.- It runs ``ResolveCaller`` itself — the requirement every pipeline fixes- last — rather than the wider set a route's own requirements would ask for,- so a handler sees exactly what the thinnest pipeline would give it. On a- route carrying ``<app_id>`` that thinnest pipeline is ``CheckAppApiEnabled``,- which loads the app; handlers read ``ctx.app`` and never load it themselves,- so the helper loads it through the same loader. Running the real pieces is- what keeps this CI-only helper from drifting away from the pipeline it- stands in for.+ Pass the route's context-loading requirements, such as+ ``CheckWorkspaceMember``, to bind the caller to its requested workspace.+ They run alongside the pipeline's fixed ``ResolveCaller`` in rank order;+ the caller is freshly loaded and does not inherit ``account.current_tenant``.+ App routes also load their app, as ``CheckAppApiEnabled`` does before the+ handler runs. Authorization itself is covered by the auth-layer tests."""ctx = Context(subject_from_auth(_account_auth(account, token_id=token_id)), session, view_args or {})if PathParam.APP_ID in ctx.view_args:load_app(ctx)- ResolveCaller().run(ctx.subject, ctx, session)+ for requirement in sorted((*requirements, ResolveCaller()), key=lambda item: item.rank):+ requirement.run(ctx.subject, ctx, session)return ctxdiff --git a/api/tests/test_containers_integration_tests/controllers/openapi/test_app_dsl.py b/api/tests/test_containers_integration_tests/controllers/openapi/test_app_dsl.pyindex fa195f29160..f65f7891916 100644--- a/api/tests/test_containers_integration_tests/controllers/openapi/test_app_dsl.py+++ b/api/tests/test_containers_integration_tests/controllers/openapi/test_app_dsl.py@@ -18,14 +18,15 @@ from controllers.openapi.app_dsl import (AppDslImportApi,AppDslImportConfirmApi,)+from controllers.openapi.auth.requirements import CheckWorkspaceMemberfrom machinery.context import RequestContextfrom models import Account, Appfrom models.model import AppModelConfig-from services.account_service import AccountService, TenantServicefrom services.app_dsl_service import CURRENT_DSL_VERSIONfrom services.app_service import AppService, CreateAppParamsfrom services.entities.dsl_entities import ImportStatusfrom tests.test_containers_integration_tests.controllers.openapi.conftest import context_for+from tests.test_containers_integration_tests.helpers import accounts as account_fixturesfrom tests.test_containers_integration_tests.helpers import generate_valid_password@@ -74,16 +75,16 @@ def external_deps() -> Generator[dict[str, object], None, None]:def _app_and_account(db_session: Session, *, mode: str = "chat") -> tuple[App, Account]:fake = Faker()- with patch("services.account_service.SystemFeatureService") as mock_account_feature_service:+ with patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service:mock_account_feature_service.is_registration_allowed.return_value = True- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session)tenant = account.current_tenantassert tenant is not Noneapp_args = CreateAppParams(@@ -219,7 +220,12 @@ class TestDslExport:with app.test_request_context(f"/openapi/v1/apps/{app_model.id}/dsl"):response, code = api.get.__handler__(api,- context_for(account, session=db_session_with_containers, view_args={"app_id": app_model.id}),+ context_for(+ account,+ session=db_session_with_containers,+ view_args={"app_id": app_model.id},+ requirements=(CheckWorkspaceMember(),),+ ),app_model.id,query=AppDslExportQuery(),)@@ -240,7 +246,12 @@ class TestDslExport:with app.test_request_context(f"/openapi/v1/apps/{app_model.id}/dsl"):result, code = api.get.__handler__(api,- context_for(account, session=db_session_with_containers, view_args={"app_id": app_model.id}),+ context_for(+ account,+ session=db_session_with_containers,+ view_args={"app_id": app_model.id},+ requirements=(CheckWorkspaceMember(),),+ ),app_model.id,query=AppDslExportQuery(),)diff --git a/api/tests/test_containers_integration_tests/controllers/openapi/test_files.py b/api/tests/test_containers_integration_tests/controllers/openapi/test_files.pyindex f340025bc4c..a74bbd8a7bd 100644--- a/api/tests/test_containers_integration_tests/controllers/openapi/test_files.py+++ b/api/tests/test_containers_integration_tests/controllers/openapi/test_files.py@@ -8,6 +8,7 @@ from sqlalchemy.orm import Sessionfrom werkzeug.datastructures import FileStoragefrom controllers.openapi._models import FileUploadPayload+from controllers.openapi.auth.requirements import CheckWorkspaceMemberfrom controllers.openapi.files import AppFileUploadApifrom models import Account, Appfrom services.app_service import AppService, CreateAppParams@@ -48,7 +49,12 @@ class TestAppFileUpload:with app.test_request_context(f"/openapi/v1/apps/{app_model.id}/files", method="POST"):result = api.post.__handler__(api,- context_for(account, session=db_session_with_containers, view_args={"app_id": app_model.id}),+ context_for(+ account,+ session=db_session_with_containers,+ view_args={"app_id": app_model.id},+ requirements=(CheckWorkspaceMember(),),+ ),app_model.id,body=body,)diff --git a/api/tests/test_containers_integration_tests/controllers/web/test_login.py b/api/tests/test_containers_integration_tests/controllers/web/test_login.pynew file mode 100644index 00000000000..6ee9e31f052--- /dev/null+++ b/api/tests/test_containers_integration_tests/controllers/web/test_login.py@@ -0,0 +1,32 @@+"""Web login rejection with the account application service and real persistence."""++from uuid import uuid4++import pytest+from flask import Flask+from sqlalchemy.orm import Session+from werkzeug.exceptions import Unauthorized++from configs import dify_config+from controllers.console import wraps+from controllers.web.login import EmailCodeLoginSendEmailApi+from enums import DeploymentEdition+from models.account import Account, AccountStatus+++def test_email_code_login_rejects_persisted_banned_account(+ flask_app_with_containers: Flask, db_session_with_containers: Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ account = Account(name="Banned", email=f"banned-{uuid4()}@example.com", status=AccountStatus.BANNED)+ db_session_with_containers.add(account)+ db_session_with_containers.commit()+ monkeypatch.setattr(dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.ENTERPRISE)+ monkeypatch.setattr(wraps, "_is_setup_completed", lambda: True)++ with (+ flask_app_with_containers.test_request_context(+ "/api/email-code-login", method="POST", json={"email": account.email, "language": "en-US"}+ ),+ pytest.raises(Unauthorized, match="Account is banned."),+ ):+ EmailCodeLoginSendEmailApi().post()diff --git a/api/tests/test_containers_integration_tests/core/rag/retrieval/test_dataset_retrieval_integration.py b/api/tests/test_containers_integration_tests/core/rag/retrieval/test_dataset_retrieval_integration.pyindex 44d7e2e4d21..215e1e46704 100644--- a/api/tests/test_containers_integration_tests/core/rag/retrieval/test_dataset_retrieval_integration.py+++ b/api/tests/test_containers_integration_tests/core/rag/retrieval/test_dataset_retrieval_integration.py@@ -10,7 +10,7 @@ from core.rag.retrieval.dataset_retrieval import DatasetRetrievalfrom core.workflow.nodes.knowledge_retrieval.retrieval import KnowledgeRetrievalRequestfrom models.dataset import Dataset, Documentfrom models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatus-from services.account_service import AccountService, TenantService+from tests.test_containers_integration_tests.helpers import accounts as account_fixturesfrom tests.test_containers_integration_tests.helpers import generate_valid_password@@ -22,14 +22,14 @@ class TestGetAvailableDatasetsIntegration:fake = Faker()# Create account and tenant- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create dataset@@ -84,14 +84,14 @@ class TestGetAvailableDatasetsIntegration:# Arrangefake = Faker()- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantdataset = Dataset(@@ -138,14 +138,14 @@ class TestGetAvailableDatasetsIntegration:# Arrangefake = Faker()- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantdataset = Dataset(@@ -192,14 +192,14 @@ class TestGetAvailableDatasetsIntegration:# Arrangefake = Faker()- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantdataset = Dataset(@@ -256,14 +256,14 @@ class TestGetAvailableDatasetsIntegration:# Arrangefake = Faker()- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantdataset = Dataset(@@ -291,28 +291,24 @@ class TestGetAvailableDatasetsIntegration:fake = Faker()# Create two accounts/tenants- account1 = AccountService.create_account(+ account1 = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(- account1, name=fake.company(), session=db_session_with_containers- )+ account_fixtures.create_owner_workspace(account1, name=fake.company(), session=db_session_with_containers)tenant1 = account1.current_tenant- account2 = AccountService.create_account(+ account2 = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(- account2, name=fake.company(), session=db_session_with_containers- )+ account_fixtures.create_owner_workspace(account2, name=fake.company(), session=db_session_with_containers)tenant2 = account2.current_tenant# Create dataset for tenant1@@ -373,14 +369,14 @@ class TestGetAvailableDatasetsIntegration:# Arrangefake = Faker()- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Don't create any datasets@@ -398,14 +394,14 @@ class TestGetAvailableDatasetsIntegration:# Arrangefake = Faker()- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create multiple datasets@@ -460,14 +456,14 @@ class TestKnowledgeRetrievalIntegration:# Arrangefake = Faker()- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantdataset = Dataset(@@ -529,14 +525,14 @@ class TestKnowledgeRetrievalIntegration:# Arrangefake = Faker()- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create dataset but no documents@@ -578,14 +574,14 @@ class TestKnowledgeRetrievalIntegration:# Arrangefake = Faker()- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantdataset = Dataset(@@ -626,7 +622,7 @@ class TestKnowledgeRetrievalIntegration:@pytest.fixturedef mock_external_service_dependencies():with (- patch("services.account_service.SystemFeatureService") as mock_account_feature_service,+ patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service,):# Setup default mock returns for account servicemock_account_feature_service.is_registration_allowed.return_value = Truediff --git a/api/tests/test_containers_integration_tests/helpers/accounts.py b/api/tests/test_containers_integration_tests/helpers/accounts.pynew file mode 100644index 00000000000..5a91212f6be--- /dev/null+++ b/api/tests/test_containers_integration_tests/helpers/accounts.py@@ -0,0 +1,45 @@+"""Build persisted test identities through the account application services."""++from sqlalchemy.orm import Session++from extensions.ext_application_services import application_services+from models.account import Account, Tenant, TenantAccountRole+++def create_account(+ *, email: str, name: str, interface_language: str, session: Session, password: str | None = None+) -> Account:+ snapshot = application_services().accounts.lifecycle.create_account(+ email, name, interface_language, password=password+ )+ account = session.get(Account, snapshot.id)+ assert account is not None+ return account+++def create_owner_workspace(account: Account, name: str | None = None, *, session: Session) -> None:+ """Seed a test identity even when self-service workspace creation is disabled."""+ application_services().workspaces.provisioning.create_owner_workspace(+ account.id, name=name, is_setup=True, if_missing=True+ )+ memberships = application_services().workspaces.management.list_memberships(account.id)+ assert memberships+ account.set_tenant_id_with_session(memberships[0].id, session=session)+++def create_workspace(*, name: str, session: Session) -> Tenant:+ workspace = application_services().workspaces.provisioning.create(name=name)+ tenant = session.get(Tenant, workspace.id)+ assert tenant is not None+ return tenant+++def join_workspace(tenant: Tenant, account: Account, session: Session, role: str) -> None:+ application_services().workspaces.members.join_member(+ workspace_id=tenant.id,+ account_id=account.id,+ email=account.email,+ role=TenantAccountRole(role),+ operator_account_id=None,+ )+ session.expire_all()diff --git a/api/tests/test_containers_integration_tests/pyrefly.toml b/api/tests/test_containers_integration_tests/pyrefly.tomlindex b86dc8e10ae..8d50124640e 100644--- a/api/tests/test_containers_integration_tests/pyrefly.toml+++ b/api/tests/test_containers_integration_tests/pyrefly.toml@@ -49,7 +49,6 @@ project-excludes = ["services/dataset_collection_binding.py","services/dataset_service_update_delete.py","services/document_service_status.py",- "services/test_account_service.py","services/test_advanced_prompt_template_service.py","services/test_agent_service.py","services/test_annotation_service.py",@@ -97,7 +96,6 @@ project-excludes = ["services/test_workflow_draft_variable_service.py","services/test_workflow_run_service.py","services/test_workflow_service.py",- "services/test_workspace_service.py","services/tools/test_mcp_tools_manage_service.py","services/tools/test_tools_transform_service.py","services/tools/test_workflow_tools_manage_service.py",diff --git a/api/tests/test_containers_integration_tests/services/account/test_authentication.py b/api/tests/test_containers_integration_tests/services/account/test_authentication.pynew file mode 100644index 00000000000..0926b5541c1--- /dev/null+++ b/api/tests/test_containers_integration_tests/services/account/test_authentication.py@@ -0,0 +1,165 @@+"""Account authentication against PostgreSQL and real Redis session indexes."""++from uuid import uuid4++import pytest+from sqlalchemy.orm import Session++from configs import dify_config+from extensions.ext_application_services import application_services+from extensions.ext_redis import redis_client+from libs.passport import PassportService+from models.account import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccountRole+from services.account_errors import (+ AccountLoginError,+ AccountNotFoundError,+ AccountPasswordError,+ InvalidRefreshTokenError,+)+from services.account_password_hasher import DefaultAccountPasswordHasher++PASSWORD = "ValidPassword123!"+++def account(db_session_with_containers: Session) -> Account:+ credentials = DefaultAccountPasswordHasher().hash(PASSWORD)+ account = Account(+ name="Session owner",+ email=f"session-{uuid4()}@example.com",+ status=AccountStatus.ACTIVE,+ password=credentials.password_hash,+ password_salt=credentials.password_salt,+ )+ workspace = Tenant(name="Session workspace")+ db_session_with_containers.add_all(+ [+ account,+ workspace,+ TenantAccountJoin(+ account_id=account.id, tenant_id=workspace.id, role=TenantAccountRole.OWNER, current=True+ ),+ ]+ )+ db_session_with_containers.commit()+ return account+++def test_authenticate_returns_persisted_account(account: Account, db_session_with_containers: Session) -> None:+ authenticated = application_services().accounts.lifecycle.authenticate(account.email, PASSWORD)+ assert (authenticated.id, authenticated.email, authenticated.name, authenticated.status) == (+ account.id,+ account.email,+ account.name,+ "active",+ )+ db_session_with_containers.refresh(account)+ assert account.password is not None+ assert account.password_salt is not None+++ ("case", "error", "message"),+ [+ ("missing", AccountNotFoundError, ""),+ ("banned", AccountLoginError, "Account is banned."),+ ("wrong-password", AccountPasswordError, "Invalid email or password."),+ ("no-password", AccountPasswordError, "Invalid email or password."),+ ],+)+def test_authenticate_rejects_invalid_credentials(+ account: Account, db_session_with_containers: Session, case: str, error: type[Exception], message: str+) -> None:+ if case == "banned":+ account.status = AccountStatus.BANNED+ elif case == "no-password":+ account.password = None+ account.password_salt = None+ db_session_with_containers.commit()+ email = f"missing-{uuid4()}@example.com" if case == "missing" else account.email+ password = "WrongPassword123!" if case == "wrong-password" else PASSWORD++ with pytest.raises(error) as raised:+ application_services().accounts.lifecycle.authenticate(email, password)+ if message:+ assert str(raised.value) == message++[email protected]("exists", [True, False])+def test_email_lookup_uses_account_repository(account: Account, exists: bool) -> None:+ email = account.email if exists else f"missing-{uuid4()}@example.com"+ found = application_services().accounts.lifecycle.get_account_by_email_with_case_fallback(email)+ if exists:+ assert found is not None+ assert (found.id, found.email, found.name, found.status) == (+ account.id,+ account.email,+ account.name,+ "active",+ )+ else:+ assert found is None+++def test_refresh_rotates_both_redis_indexes_and_rejects_reuse(account: Account) -> None:+ services = application_services().accounts+ initial = services.lifecycle.login(account.id, ip_address="127.0.0.1")+ account_key = f"account_refresh_token:{account.id}"+ old_key = f"refresh_token:{initial.refresh_token}"+ assert redis_client.get(account_key) == initial.refresh_token.encode()+ assert redis_client.get(old_key) == account.id.encode()++ refreshed = services.authentication.refresh(initial.refresh_token)++ new_key = f"refresh_token:{refreshed.refresh_token}"+ assert refreshed.refresh_token != initial.refresh_token+ assert PassportService().verify(refreshed.access_token)["user_id"] == account.id+ assert refreshed.csrf_token+ assert redis_client.get(old_key) is None+ assert redis_client.get(account_key) == refreshed.refresh_token.encode()+ assert redis_client.get(new_key) == account.id.encode()+ for key in (account_key, new_key):+ assert 0 < redis_client.ttl(key) <= dify_config.REFRESH_TOKEN_EXPIRE_DAYS * 86400+ with pytest.raises(InvalidRefreshTokenError, match="Invalid refresh token"):+ services.authentication.refresh(initial.refresh_token)+ assert redis_client.get(new_key) == account.id.encode()+++def test_logout_revokes_real_redis_session_and_is_idempotent(account: Account) -> None:+ services = application_services().accounts+ tokens = services.lifecycle.login(account.id, ip_address="127.0.0.1")+ account_key = f"account_refresh_token:{account.id}"+ refresh_key = f"refresh_token:{tokens.refresh_token}"+ assert redis_client.exists(account_key)+ assert redis_client.exists(refresh_key)++ services.authentication.logout(account.id)++ assert redis_client.get(account_key) is None+ assert redis_client.get(refresh_key) is None+ with pytest.raises(InvalidRefreshTokenError):+ services.authentication.refresh(tokens.refresh_token)+ services.authentication.logout(account.id)+ assert redis_client.get(account_key) is None++[email protected]("reason", ["unknown", "expired", "deleted-account", "banned-account"])+def test_refresh_rejects_invalid_persisted_sessions(+ account: Account, db_session_with_containers: Session, reason: str+) -> None:+ services = application_services().accounts+ tokens = services.lifecycle.login(account.id, ip_address="127.0.0.1")+ refresh_token = tokens.refresh_token+ if reason == "unknown":+ refresh_token = f"unknown-{uuid4()}"+ elif reason == "expired":+ redis_client.pexpire(f"refresh_token:{refresh_token}", 0)+ elif reason == "deleted-account":+ db_session_with_containers.delete(account)+ db_session_with_containers.commit()+ else:+ account.status = AccountStatus.BANNED+ db_session_with_containers.commit()++ with pytest.raises(InvalidRefreshTokenError):+ services.authentication.refresh(refresh_token)diff --git a/api/tests/test_containers_integration_tests/services/dataset_service_update_delete.py b/api/tests/test_containers_integration_tests/services/dataset_service_update_delete.pyindex 587258f5864..27e27d44906 100644--- a/api/tests/test_containers_integration_tests/services/dataset_service_update_delete.py+++ b/api/tests/test_containers_integration_tests/services/dataset_service_update_delete.py@@ -17,7 +17,7 @@ from models import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccofrom models.dataset import AppDatasetJoin, Dataset, DatasetPermissionEnumfrom models.enums import DataSourceTypefrom models.model import App-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.knowledge.dataset_service import DatasetServicefrom services.knowledge.resource_scope import DatasetRefdiff --git a/api/tests/test_containers_integration_tests/services/test_account_oauth_identity_lock.py b/api/tests/test_containers_integration_tests/services/test_account_oauth_identity_lock.pyindex e0c40d40576..5737968c525 100644--- a/api/tests/test_containers_integration_tests/services/test_account_oauth_identity_lock.py+++ b/api/tests/test_containers_integration_tests/services/test_account_oauth_identity_lock.py@@ -7,9 +7,9 @@ from uuid import uuid4import pytestfrom extensions.ext_redis import redis_client-from services import account_oauth_adapters+from services.account import oauth_adapters as account_oauth_adapters+from services.account.oauth_adapters import RedisOAuthAccountClaimLockfrom services.account_errors import OAuthIdentityLockUnavailableError-from services.account_oauth_adapters import RedisOAuthAccountClaimLock@pytest.mark.usefixtures("flask_app_with_containers")diff --git a/api/tests/test_containers_integration_tests/services/test_account_service.py b/api/tests/test_containers_integration_tests/services/test_account_service.pydeleted file mode 100644index 28f8e7fd55b..00000000000--- a/api/tests/test_containers_integration_tests/services/test_account_service.py+++ /dev/null@@ -1,2765 +0,0 @@-import json-from hashlib import sha256-from unittest.mock import MagicMock, patch--import pytest-from faker import Faker-from sqlalchemy.orm import Session-from werkzeug.exceptions import Unauthorized--from configs import dify_config-from controllers.console.error import NotAllowedCreateWorkspace-from enums import DeploymentEdition-from extensions.ext_application_services import application_services-from extensions.ext_redis import redis_client-from models import AccountStatus, App, Dataset, TenantAccountJoin, TenantStatus-from services import account_errors-from services.account_login_adapters import RedisAccountSessionGateway-from services.account_service import AccountService, RegisterService, TenantService, TokenPair-from services.entities.account_login_entities import AuthTokenPair-from services.errors.account import (- AccountAlreadyInTenantError,- AccountNotFoundError,- AccountRegisterError,- SeatsLimitExceededError,-)-from services.errors.workspace import WorkSpaceNotAllowedCreateError, WorkspacesLimitExceededError-from tests.test_containers_integration_tests.helpers import generate_valid_password---class TestAccountService:- """Integration tests for AccountService using testcontainers."""-- @pytest.fixture- def mock_external_service_dependencies(self):- """Mock setup for external service dependencies."""- with (- 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 returns- mock_feature_service.is_registration_allowed.return_value = True- mock_feature_service.is_workspace_creation_allowed.return_value = True- mock_feature_service.get_license.return_value.workspaces.is_available.return_value = True- mock_feature_service.get_license.return_value.seats.is_available.return_value = True- mock_billing_service.is_email_in_freeze.return_value = False- 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_service-- yield {- "feature_service": mock_feature_service,- "billing_service": mock_billing_service,- "passport_service": mock_passport_service,- }-- def test_create_account(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test account creation with a password.- """- 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-- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )- assert account.email == email- assert account.status == AccountStatus.ACTIVE-- def test_create_account_without_password(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test account creation without password (for OAuth users).- """- fake = Faker()- email = fake.email()- name = fake.name()- # 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-- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=None,- session=db_session_with_containers,- )- assert account.email == email- assert account.password is None- assert account.password_salt is None-- def test_create_account_password_invalid_new_password(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test account create with invalid new password format.- """- fake = Faker()- email = fake.email()- name = fake.name()- # 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-- # Test with too short password (assuming minimum length validation)- with pytest.raises(ValueError): # Password validation error- AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password="invalid_new_password",- session=db_session_with_containers,- )-- def test_create_account_registration_disabled(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test account creation when registration is disabled.- """- fake = Faker()- email = fake.email()- name = fake.name()- # Setup mocks to disable registration- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = False-- with pytest.raises(AccountNotFoundError):- AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=generate_valid_password(fake),- session=db_session_with_containers,- )-- def test_create_account_email_in_freeze(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test account creation when email is in freeze period.- """- 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 = True- dify_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD-- with pytest.raises(AccountRegisterError):- AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- dify_config.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITY # Reset config for other tests-- def test_create_account_and_tenant(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test account creation with automatic tenant creation.- """- 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["feature_service"].is_workspace_creation_allowed.return_value = True- mock_external_service_dependencies[- "feature_service"- ].get_license.return_value.workspaces.is_available.return_value = True- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False- account = AccountService.create_account_and_tenant(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- assert account.email == email-- # Verify tenant was created and linked-- tenant_join = db_session_with_containers.query(TenantAccountJoin).filter_by(account_id=account.id).first()- assert tenant_join is not None- assert tenant_join.role == "owner"-- def test_create_account_and_tenant_workspace_creation_disabled(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test account creation when workspace creation is disabled.- """- 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["feature_service"].is_workspace_creation_allowed.return_value = False- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- with pytest.raises(WorkSpaceNotAllowedCreateError):- AccountService.create_account_and_tenant(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- def test_create_account_and_tenant_workspace_limit_exceeded(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test account creation when workspace limit is exceeded.- """- 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["feature_service"].is_workspace_creation_allowed.return_value = True- mock_external_service_dependencies[- "feature_service"- ].get_license.return_value.workspaces.is_available.return_value = False- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- with pytest.raises(WorkspacesLimitExceededError):- AccountService.create_account_and_tenant(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- def test_create_account_seats_limit_exceeded(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test account creation when the licensed seats limit is exceeded.- """- 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[- "feature_service"- ].get_license.return_value.seats.is_available.return_value = False- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- with pytest.raises(SeatsLimitExceededError):- AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- def test_update_login_info(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test updating login information.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- ip_address = fake.ipv4()- # 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,- )-- # Update login info- AccountService.update_login_info(account, db_session_with_containers, ip_address=ip_address)-- # Verify login info was updated-- db_session_with_containers.refresh(account)- assert account.last_login_ip == ip_address- assert account.last_login_at is not None-- def test_login_success(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test successful login with token generation.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- ip_address = fake.ipv4()- # 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- mock_external_service_dependencies["passport_service"].return_value.issue.return_value = "mock_access_token"-- # Create account- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- # Login- token_pair = AccountService.login(account, ip_address=ip_address, session=db_session_with_containers)-- assert isinstance(token_pair, TokenPair)- assert token_pair.access_token == "mock_access_token"- assert token_pair.refresh_token is not None-- # Verify passport service was called with correct parameters- mock_passport = mock_external_service_dependencies["passport_service"].return_value- mock_passport.issue.assert_called_once()- call_args = mock_passport.issue.call_args[0][0]- assert call_args["user_id"] == account.id- assert call_args["iss"] is not None- assert call_args["sub"] == "Console API Passport"-- def test_login_pending_account_activation(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test login 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- mock_external_service_dependencies["passport_service"].return_value.issue.return_value = "mock_access_token"-- # 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()-- # Login should activate the account- token_pair = AccountService.login(account, session=db_session_with_containers)-- db_session_with_containers.refresh(account)- assert account.status == AccountStatus.ACTIVE-- def test_authentication_service_logout(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test logout functionality.- """- 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- mock_external_service_dependencies["passport_service"].return_value.issue.return_value = "mock_access_token"-- # Create account- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- 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)-- application_services().accounts.authentication.logout(account.id)-- # Verify refresh token was deleted from Redis- refresh_token_key = f"account_refresh_token:{account.id}"- assert redis_client.get(refresh_token_key) is None-- def test_authentication_service_refresh_success(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test successful token refresh.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- tenant_name = fake.company()- # 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- mock_external_service_dependencies["passport_service"].return_value.issue.return_value = "new_mock_access_token"-- # Create account- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )- # Create associated Tenant- TenantService.create_owner_tenant_if_not_exist(- account=account, name=tenant_name, is_setup=True, session=db_session_with_containers- )-- initial_token_pair = RedisAccountSessionGateway(redis=redis_client).issue(account.id)-- new_token_pair = application_services().accounts.authentication.refresh(initial_token_pair.refresh_token)-- 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_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(account_errors.InvalidRefreshTokenError, match="Invalid refresh token"):- application_services().accounts.authentication.refresh(invalid_token)-- def test_authentication_service_refresh_rejects_missing_account(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test refresh token with valid token but invalid 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- mock_external_service_dependencies["passport_service"].return_value.issue.return_value = "mock_access_token"-- # Create account- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- token_pair = RedisAccountSessionGateway(redis=redis_client).issue(account.id)-- # Delete account-- db_session_with_containers.delete(account)- db_session_with_containers.commit()-- 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):- """- Test loading user by ID successfully.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- tenant_name = fake.company()- # 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,- )- # Create associated Tenant- TenantService.create_owner_tenant_if_not_exist(- account=account, name=tenant_name, is_setup=True, session=db_session_with_containers- )-- # Load user- loaded_user = AccountService.load_user(account.id, db_session_with_containers)-- assert loaded_user is not None- assert loaded_user.id == account.id- assert loaded_user.email == account.email-- def test_load_user_not_found(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test loading non-existent user.- """- fake = Faker()- non_existent_user_id = fake.uuid4()- loaded_user = AccountService.load_user(non_existent_user_id, db_session_with_containers)- assert loaded_user is None-- def test_load_user_banned_account(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test loading banned user 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.load_user(account.id, db_session_with_containers)-- def test_get_account_jwt_token(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test JWT token generation for 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- mock_external_service_dependencies["passport_service"].return_value.issue.return_value = "mock_jwt_token"-- # Create account- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- # Generate JWT token- token = AccountService.get_account_jwt_token(account)-- assert token == "mock_jwt_token"-- # Verify passport service was called with correct parameters- mock_passport = mock_external_service_dependencies["passport_service"].return_value- mock_passport.issue.assert_called_once()- call_args = mock_passport.issue.call_args[0][0]- assert call_args["user_id"] == account.id- assert call_args["iss"] is not None- assert call_args["sub"] == "Console API Passport"-- def test_load_logged_in_account(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test loading logged in account by ID.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- tenant_name = fake.company()- # 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,- )- # Create associated Tenant- TenantService.create_owner_tenant_if_not_exist(- account=account, name=tenant_name, is_setup=True, session=db_session_with_containers- )-- # Load logged in account- loaded_account = AccountService.load_logged_in_account(- account_id=account.id, session=db_session_with_containers- )-- assert loaded_account is not None- assert loaded_account.id == account.id---class TestTenantService:- """Integration tests for TenantService using testcontainers."""-- @pytest.fixture- def mock_external_service_dependencies(self):- """Mock setup for external service dependencies."""- with (- patch("services.account_service.SystemFeatureService") as mock_feature_service,- patch("services.account_service.BillingService") as mock_billing_service,- ):- # Setup default mock returns- mock_feature_service.is_workspace_creation_allowed.return_value = True- mock_feature_service.get_license.return_value.workspaces.is_available.return_value = True- mock_feature_service.get_license.return_value.seats.is_available.return_value = True- mock_billing_service.is_email_in_freeze.return_value = False-- yield {- "feature_service": mock_feature_service,- "billing_service": mock_billing_service,- }-- def test_create_tenant_success(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test successful tenant creation with default settings.- """- fake = Faker()- tenant_name = fake.company()- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)-- assert tenant.name == tenant_name- assert tenant.plan == "basic"- assert tenant.status == "normal"- assert tenant.encrypt_public_key is not None-- def test_create_tenant_workspace_creation_disabled(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test tenant creation when workspace creation is disabled.- """- fake = Faker()- tenant_name = fake.company()- # Setup mocks to disable workspace creation- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = False-- with pytest.raises(NotAllowedCreateWorkspace): # NotAllowedCreateWorkspace exception- TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)-- def test_create_tenant_with_custom_name(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test tenant creation with custom name and setup flag.- """- fake = Faker()- custom_tenant_name = fake.company()- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = False-- # Create tenant with setup flag (should bypass workspace creation restriction)- tenant = TenantService.create_tenant(- name=custom_tenant_name, is_setup=True, is_from_dashboard=True, session=db_session_with_containers- )-- assert tenant.name == custom_tenant_name- assert tenant.plan == "basic"- assert tenant.status == "normal"- assert tenant.encrypt_public_key is not None-- def test_create_tenant_member_success(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test successful tenant member creation.- """- fake = Faker()- tenant_name = fake.company()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant and account- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- # Create tenant member- tenant_member = TenantService.create_tenant_member(tenant, account, db_session_with_containers, role="admin")-- assert tenant_member.tenant_id == tenant.id- assert tenant_member.account_id == account.id- assert tenant_member.role == "admin"-- def test_create_tenant_member_duplicate_owner(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test creating duplicate owner for a tenant (should fail).- """- fake = Faker()- tenant_name = fake.company()- email1 = fake.email()- name1 = fake.name()- password1 = generate_valid_password(fake)- email2 = fake.email()- name2 = fake.name()- password2 = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant and accounts- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- account1 = AccountService.create_account(- email=email1,- name=name1,- interface_language="en-US",- password=password1,- session=db_session_with_containers,- )- account2 = AccountService.create_account(- email=email2,- name=name2,- interface_language="en-US",- password=password2,- session=db_session_with_containers,- )-- # Create first owner- TenantService.create_tenant_member(tenant, account1, db_session_with_containers, role="owner")-- # Try to create second owner (should fail)- with pytest.raises(Exception, match="Tenant already has an owner"):- TenantService.create_tenant_member(tenant, account2, db_session_with_containers, role="owner")-- def test_create_tenant_member_existing_member(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test updating role for existing tenant member.- """- fake = Faker()- tenant_name = fake.company()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant and account- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- # Create member with initial role- tenant_member1 = TenantService.create_tenant_member(tenant, account, db_session_with_containers, role="normal")- assert tenant_member1.role == "normal"-- # Update member role- tenant_member2 = TenantService.create_tenant_member(tenant, account, db_session_with_containers, role="editor")- assert tenant_member2.tenant_id == tenant_member1.tenant_id- assert tenant_member2.account_id == tenant_member1.account_id- assert tenant_member2.role == "editor"-- def test_get_join_tenants_success(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test getting join tenants for an account.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- tenant1_name = fake.company()- tenant2_name = fake.company()- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create account and tenants- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )- tenant1 = TenantService.create_tenant(name=tenant1_name, session=db_session_with_containers)- tenant2 = TenantService.create_tenant(name=tenant2_name, session=db_session_with_containers)-- # Add account to both tenants- TenantService.create_tenant_member(tenant1, account, db_session_with_containers, role="normal")- TenantService.create_tenant_member(tenant2, account, db_session_with_containers, role="admin")-- # Get join tenants- join_tenants = TenantService.get_join_tenants(account, session=db_session_with_containers)-- assert len(join_tenants) == 2- tenant_names = [tenant.name for tenant in join_tenants]- assert tenant1_name in tenant_names- assert tenant2_name in tenant_names-- def test_switch_tenant_success(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test successful tenant switching.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- tenant1_name = fake.company()- tenant2_name = fake.company()- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create account and tenants- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )- tenant1 = TenantService.create_tenant(name=tenant1_name, session=db_session_with_containers)- tenant2 = TenantService.create_tenant(name=tenant2_name, session=db_session_with_containers)-- # Add account to both tenants- TenantService.create_tenant_member(tenant1, account, db_session_with_containers, role="owner")- TenantService.create_tenant_member(tenant2, account, db_session_with_containers, role="admin")-- # Set initial current tenant- account.set_current_tenant_with_session(tenant1, session=db_session_with_containers)-- db_session_with_containers.commit()-- # Switch to second tenant- TenantService.switch_tenant(account, tenant2.id, session=db_session_with_containers)-- # Verify tenant was switched- db_session_with_containers.refresh(account)- assert account.current_tenant_id == tenant2.id-- def test_switch_tenant_no_tenant_id(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test tenant switching without providing tenant ID.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create account- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- # Try to switch tenant without providing tenant ID- with pytest.raises(ValueError, match="Tenant ID must be provided"):- TenantService.switch_tenant(account, None, session=db_session_with_containers)-- def test_switch_tenant_account_not_member(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test switching to a tenant where account is not a member.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- tenant_name = fake.company()- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create account and tenant- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)-- # Try to switch to tenant where account is not a member- with pytest.raises(Exception, match="Tenant not found or account is not a member of the tenant"):- TenantService.switch_tenant(account, tenant.id, session=db_session_with_containers)-- def test_has_roles_success(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test checking if tenant has specific roles.- """- fake = Faker()- tenant_name = fake.company()- owner_email = fake.email()- owner_name = fake.name()- owner_password = generate_valid_password(fake)- admin_email = fake.email()- admin_name = fake.name()- admin_password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant and accounts- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- owner_account = AccountService.create_account(- email=owner_email,- name=owner_name,- interface_language="en-US",- password=owner_password,- session=db_session_with_containers,- )- admin_account = AccountService.create_account(- email=admin_email,- name=admin_name,- interface_language="en-US",- password=admin_password,- session=db_session_with_containers,- )-- # Add members with different roles- TenantService.create_tenant_member(tenant, owner_account, db_session_with_containers, role="owner")- TenantService.create_tenant_member(tenant, admin_account, db_session_with_containers, role="admin")-- # Check if tenant has owner role- from models.account import TenantAccountRole-- has_owner = TenantService.has_roles(tenant, [TenantAccountRole.OWNER], session=db_session_with_containers)- assert has_owner is True-- # Check if tenant has admin role- has_admin = TenantService.has_roles(tenant, [TenantAccountRole.ADMIN], session=db_session_with_containers)- assert has_admin is True-- # Check if tenant has normal role (should be False)- has_normal = TenantService.has_roles(tenant, [TenantAccountRole.NORMAL], session=db_session_with_containers)- assert has_normal is False-- def test_has_roles_invalid_role_type(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test checking roles with invalid role type.- """- fake = Faker()- tenant_name = fake.company()- invalid_role = fake.word()- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)-- # Try to check roles with invalid role type- with pytest.raises(ValueError, match="all roles must be TenantAccountRole"):- TenantService.has_roles(tenant, [invalid_role], session=db_session_with_containers)-- def test_get_user_role_success(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test getting user role in a tenant.- """- fake = Faker()- tenant_name = fake.company()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant and account- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- # Add account to tenant with specific role- TenantService.create_tenant_member(tenant, account, db_session_with_containers, role="editor")-- # Get user role- user_role = TenantService.get_user_role(account, tenant, session=db_session_with_containers)-- assert user_role == "editor"-- def test_check_member_permission_success(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test checking member permission successfully.- """- fake = Faker()- tenant_name = fake.company()- owner_email = fake.email()- owner_name = fake.name()- owner_password = generate_valid_password(fake)- member_email = fake.email()- member_name = fake.name()- member_password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant and accounts- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- owner_account = AccountService.create_account(- email=owner_email,- name=owner_name,- interface_language="en-US",- password=owner_password,- session=db_session_with_containers,- )- member_account = AccountService.create_account(- email=member_email,- name=member_name,- interface_language="en-US",- password=member_password,- session=db_session_with_containers,- )-- # Add members with different roles- TenantService.create_tenant_member(tenant, owner_account, db_session_with_containers, role="owner")- TenantService.create_tenant_member(tenant, member_account, db_session_with_containers, role="normal")-- # Check owner permission to add member (should succeed)- TenantService.check_member_permission(- tenant, owner_account, member_account, "add", session=db_session_with_containers- )-- def test_check_member_permission_invalid_action(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test checking member permission with invalid action.- """- fake = Faker()- tenant_name = fake.company()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- invalid_action = "invalid_action_that_doesnt_exist"- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant and account- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- # Add account to tenant- TenantService.create_tenant_member(tenant, account, db_session_with_containers, role="owner")-- # Try to check permission with invalid action- with pytest.raises(Exception, match="Invalid action"):- TenantService.check_member_permission(- tenant, account, None, invalid_action, session=db_session_with_containers- )-- def test_check_member_permission_operate_self(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test checking member permission when trying to operate self.- """- fake = Faker()- tenant_name = fake.company()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant and account- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- # Add account to tenant- TenantService.create_tenant_member(tenant, account, db_session_with_containers, role="owner")-- # Try to check permission to operate self- with pytest.raises(Exception, match="Cannot operate self"):- TenantService.check_member_permission(- tenant, account, account, "remove", session=db_session_with_containers- )-- def test_remove_member_from_tenant_success(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test successful member removal from tenant (should sync to enterprise).- """- fake = Faker()- tenant_name = fake.company()- owner_email = fake.email()- owner_name = fake.name()- owner_password = generate_valid_password(fake)- member_email = fake.email()- member_name = fake.name()- member_password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant and accounts- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- owner_account = AccountService.create_account(- email=owner_email,- name=owner_name,- interface_language="en-US",- password=owner_password,- session=db_session_with_containers,- )- member_account = AccountService.create_account(- email=member_email,- name=member_name,- interface_language="en-US",- password=member_password,- session=db_session_with_containers,- )-- # Add members with different roles- TenantService.create_tenant_member(tenant, owner_account, db_session_with_containers, role="owner")- TenantService.create_tenant_member(tenant, member_account, db_session_with_containers, role="normal")-- app = App(- tenant_id=tenant.id,- name="Member app",- mode="chat",- enable_site=True,- enable_api=True,- created_by=member_account.id,- maintainer=member_account.id,- )- dataset = Dataset(- tenant_id=tenant.id,- name="Member dataset",- created_by=member_account.id,- maintainer=member_account.id,- )- db_session_with_containers.add_all([app, dataset])- db_session_with_containers.commit()-- # Remove member- with (- patch("services.enterprise.account_deletion_sync.sync_workspace_member_removal") as mock_sync,- patch(- "services.account_service.AccountService.get_rbac_workspace_owner_account_id",- return_value=owner_account.id,- ),- ):- mock_sync.return_value = True-- TenantService.remove_member_from_tenant(- tenant, member_account, owner_account, session=db_session_with_containers- )-- # Verify sync was called- mock_sync.assert_called_once_with(- workspace_id=tenant.id, member_id=member_account.id, source="workspace_member_removed"- )-- # Verify member was removed- from models.account import TenantAccountJoin-- member_join = (- db_session_with_containers.query(TenantAccountJoin)- .filter_by(tenant_id=tenant.id, account_id=member_account.id)- .first()- )- assert member_join is None- db_session_with_containers.refresh(app)- db_session_with_containers.refresh(dataset)- assert app.created_by == member_account.id- assert app.maintainer == owner_account.id- assert dataset.created_by == member_account.id- assert dataset.maintainer == owner_account.id-- def test_remove_member_from_tenant_operate_self(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test removing member when trying to operate self.- """- fake = Faker()- tenant_name = fake.company()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant and account- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- # Add account to tenant- TenantService.create_tenant_member(tenant, account, db_session_with_containers, role="owner")-- # Try to remove self- with pytest.raises(Exception, match="Cannot operate self"):- TenantService.remove_member_from_tenant(tenant, account, account, session=db_session_with_containers)-- def test_remove_member_from_tenant_not_member(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test removing member who is not in the tenant.- """- fake = Faker()- tenant_name = fake.company()- owner_email = fake.email()- owner_name = fake.name()- owner_password = generate_valid_password(fake)- non_member_email = fake.email()- non_member_name = fake.name()- non_member_password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant and accounts- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- owner_account = AccountService.create_account(- email=owner_email,- name=owner_name,- interface_language="en-US",- password=owner_password,- session=db_session_with_containers,- )- non_member_account = AccountService.create_account(- email=non_member_email,- name=non_member_name,- interface_language="en-US",- password=non_member_password,- session=db_session_with_containers,- )-- # Add only owner to tenant- TenantService.create_tenant_member(tenant, owner_account, db_session_with_containers, role="owner")-- # Try to remove non-member- with pytest.raises(Exception, match="Member not in tenant"):- TenantService.remove_member_from_tenant(- tenant, non_member_account, owner_account, session=db_session_with_containers- )-- def test_update_member_role_success(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test successful member role update.- """- fake = Faker()- tenant_name = fake.company()- owner_email = fake.email()- owner_name = fake.name()- owner_password = generate_valid_password(fake)- member_email = fake.email()- member_name = fake.name()- member_password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant and accounts- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- owner_account = AccountService.create_account(- email=owner_email,- name=owner_name,- interface_language="en-US",- password=owner_password,- session=db_session_with_containers,- )- member_account = AccountService.create_account(- email=member_email,- name=member_name,- interface_language="en-US",- password=member_password,- session=db_session_with_containers,- )-- # Add members with different roles- TenantService.create_tenant_member(tenant, owner_account, db_session_with_containers, role="owner")- TenantService.create_tenant_member(tenant, member_account, db_session_with_containers, role="normal")-- # Update member role- TenantService.update_member_role(- tenant, member_account, "admin", owner_account, session=db_session_with_containers- )-- # Verify role was updated- from models.account import TenantAccountJoin-- member_join = (- db_session_with_containers.query(TenantAccountJoin)- .filter_by(tenant_id=tenant.id, account_id=member_account.id)- .first()- )- assert member_join.role == "admin"-- def test_update_member_role_to_owner(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test updating member role to owner (should change current owner to normal).- """- fake = Faker()- tenant_name = fake.company()- owner_email = fake.email()- owner_name = fake.name()- owner_password = generate_valid_password(fake)- member_email = fake.email()- member_name = fake.name()- member_password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant and accounts- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- owner_account = AccountService.create_account(- email=owner_email,- name=owner_name,- interface_language="en-US",- password=owner_password,- session=db_session_with_containers,- )- member_account = AccountService.create_account(- email=member_email,- name=member_name,- interface_language="en-US",- password=member_password,- session=db_session_with_containers,- )-- # Add members with different roles- TenantService.create_tenant_member(tenant, owner_account, db_session_with_containers, role="owner")- TenantService.create_tenant_member(tenant, member_account, db_session_with_containers, role="admin")-- # Update member role to owner- TenantService.update_member_role(- tenant, member_account, "owner", owner_account, session=db_session_with_containers- )-- # Verify roles were updated correctly- from models.account import TenantAccountJoin-- owner_join = (- db_session_with_containers.query(TenantAccountJoin)- .filter_by(tenant_id=tenant.id, account_id=owner_account.id)- .first()- )- member_join = (- db_session_with_containers.query(TenantAccountJoin)- .filter_by(tenant_id=tenant.id, account_id=member_account.id)- .first()- )- assert owner_join.role == "normal"- assert member_join.role == "owner"-- def test_update_member_role_already_assigned(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test updating member role to already assigned role.- """- fake = Faker()- tenant_name = fake.company()- owner_email = fake.email()- owner_name = fake.name()- owner_password = generate_valid_password(fake)- member_email = fake.email()- member_name = fake.name()- member_password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant and accounts- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- owner_account = AccountService.create_account(- email=owner_email,- name=owner_name,- interface_language="en-US",- password=owner_password,- session=db_session_with_containers,- )- member_account = AccountService.create_account(- email=member_email,- name=member_name,- interface_language="en-US",- password=member_password,- session=db_session_with_containers,- )-- # Add members with different roles- TenantService.create_tenant_member(tenant, owner_account, db_session_with_containers, role="owner")- TenantService.create_tenant_member(tenant, member_account, db_session_with_containers, role="admin")-- # Try to update member role to already assigned role- with pytest.raises(Exception, match="The provided role is already assigned to the member"):- TenantService.update_member_role(- tenant, member_account, "admin", owner_account, session=db_session_with_containers- )-- def test_create_owner_tenant_if_not_exist_new_user(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test creating owner tenant for new user without existing tenants.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- workspace_name = fake.company()- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True- mock_external_service_dependencies[- "feature_service"- ].get_license.return_value.workspaces.is_available.return_value = True-- # Create account- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- # Create owner tenant- TenantService.create_owner_tenant_if_not_exist(account, name=workspace_name, session=db_session_with_containers)-- # Verify tenant was created and linked- from models.account import TenantAccountJoin-- tenant_join = db_session_with_containers.query(TenantAccountJoin).filter_by(account_id=account.id).first()- assert tenant_join is not None- assert tenant_join.role == "owner"- assert account.current_tenant is not None- assert account.current_tenant.name == workspace_name-- def test_create_owner_tenant_if_not_exist_existing_tenant(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test creating owner tenant when user already has a tenant.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- existing_tenant_name = fake.company()- new_workspace_name = fake.company()- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True- mock_external_service_dependencies[- "feature_service"- ].get_license.return_value.workspaces.is_available.return_value = True-- # Create account and existing tenant- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )- existing_tenant = TenantService.create_tenant(name=existing_tenant_name, session=db_session_with_containers)- TenantService.create_tenant_member(existing_tenant, account, db_session_with_containers, role="owner")- account.set_current_tenant_with_session(existing_tenant, session=db_session_with_containers)-- db_session_with_containers.commit()-- # Try to create owner tenant again (should not create new one)- TenantService.create_owner_tenant_if_not_exist(- account, name=new_workspace_name, session=db_session_with_containers- )-- # Verify no new tenant was created- tenant_joins = db_session_with_containers.query(TenantAccountJoin).filter_by(account_id=account.id).all()- assert len(tenant_joins) == 1- assert account.current_tenant.id == existing_tenant.id-- def test_create_owner_tenant_if_not_exist_workspace_disabled(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test creating owner tenant when workspace creation is disabled.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- workspace_name = fake.company()- # Setup mocks to disable workspace creation- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = False-- # Create account- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- # Try to create owner tenant (should fail)- with pytest.raises(WorkSpaceNotAllowedCreateError): # WorkSpaceNotAllowedCreateError exception- TenantService.create_owner_tenant_if_not_exist(- account, name=workspace_name, session=db_session_with_containers- )-- def test_get_tenant_members_success(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test getting tenant members successfully.- """- fake = Faker()- tenant_name = fake.company()- owner_email = fake.email()- owner_name = fake.name()- owner_password = generate_valid_password(fake)- admin_email = fake.email()- admin_name = fake.name()- admin_password = generate_valid_password(fake)- normal_email = fake.email()- normal_name = fake.name()- normal_password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant and accounts- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- owner_account = AccountService.create_account(- email=owner_email,- name=owner_name,- interface_language="en-US",- password=owner_password,- session=db_session_with_containers,- )- admin_account = AccountService.create_account(- email=admin_email,- name=admin_name,- interface_language="en-US",- password=admin_password,- session=db_session_with_containers,- )- normal_account = AccountService.create_account(- email=normal_email,- name=normal_name,- interface_language="en-US",- password=normal_password,- session=db_session_with_containers,- )-- # Add members with different roles- TenantService.create_tenant_member(tenant, owner_account, db_session_with_containers, role="owner")- TenantService.create_tenant_member(tenant, admin_account, db_session_with_containers, role="admin")- TenantService.create_tenant_member(tenant, normal_account, db_session_with_containers, role="normal")-- # Get tenant members- members = TenantService.get_tenant_members(tenant, session=db_session_with_containers)-- assert len(members) == 3- member_emails = [member.email for member in members]- assert owner_email in member_emails- assert admin_email in member_emails- assert normal_email in member_emails-- # Verify roles are set correctly- for member in members:- if member.email == owner_email:- assert member.role == "owner"- elif member.email == admin_email:- assert member.role == "admin"- elif member.email == normal_email:- assert member.role == "normal"-- def test_get_dataset_operator_members_success(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test getting dataset operator members successfully.- """- fake = Faker()- tenant_name = fake.company()- owner_email = fake.email()- owner_name = fake.name()- owner_password = generate_valid_password(fake)- operator_email = fake.email()- operator_name = fake.name()- operator_password = generate_valid_password(fake)- normal_email = fake.email()- normal_name = fake.name()- normal_password = generate_valid_password(fake)- # Setup mocks- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True-- # Create tenant and accounts- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- owner_account = AccountService.create_account(- email=owner_email,- name=owner_name,- interface_language="en-US",- password=owner_password,- session=db_session_with_containers,- )- dataset_operator_account = AccountService.create_account(- email=operator_email,- name=operator_name,- interface_language="en-US",- password=operator_password,- session=db_session_with_containers,- )- normal_account = AccountService.create_account(- email=normal_email,- name=normal_name,- interface_language="en-US",- password=normal_password,- session=db_session_with_containers,- )-- # Add members with different roles- TenantService.create_tenant_member(tenant, owner_account, db_session_with_containers, role="owner")- TenantService.create_tenant_member(- tenant, dataset_operator_account, db_session_with_containers, role="dataset_operator"- )- TenantService.create_tenant_member(tenant, normal_account, db_session_with_containers, role="normal")-- # Get dataset operator members- dataset_operators = TenantService.get_dataset_operator_members(tenant, session=db_session_with_containers)-- assert len(dataset_operators) == 1- assert dataset_operators[0].email == operator_email- assert dataset_operators[0].role == "dataset_operator"---class TestRegisterService:- """Integration tests for RegisterService using testcontainers."""-- @pytest.fixture- def mock_external_service_dependencies(self):- """Mock setup for external service dependencies."""- with (- 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,- ):- # Setup default mock returns- mock_feature_service.is_registration_allowed.return_value = True- mock_feature_service.is_workspace_creation_allowed.return_value = True- mock_feature_service.get_license.return_value.workspaces.is_available.return_value = True- mock_feature_service.get_license.return_value.seats.is_available.return_value = True- mock_billing_service.is_email_in_freeze.return_value = False- mock_passport_service.return_value.issue.return_value = "mock_jwt_token"-- yield {- "feature_service": mock_feature_service,- "billing_service": mock_billing_service,- "passport_service": mock_passport_service,- }-- def test_setup_success(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test successful system setup with account creation and tenant setup.- """- fake = Faker()- admin_email = fake.email()- admin_name = fake.name()- admin_password = generate_valid_password(fake)- ip_address = fake.ipv4()- # 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-- from models.model import DifySetup-- db_session_with_containers.query(DifySetup).delete()- db_session_with_containers.commit()-- # Execute setup- RegisterService.setup(- email=admin_email,- name=admin_name,- password=admin_password,- ip_address=ip_address,- language="en-US",- session=db_session_with_containers,- )-- # Verify account was created- from models import Account-- account = db_session_with_containers.query(Account).filter_by(email=admin_email).first()- assert account is not None- assert account.name == admin_name- assert account.last_login_ip == ip_address- assert account.initialized_at is not None- assert account.status == "active"-- # Verify DifySetup was created- dify_setup = db_session_with_containers.query(DifySetup).first()- assert dify_setup is not None-- # Verify tenant was created and linked- from models.account import TenantAccountJoin-- tenant_join = db_session_with_containers.query(TenantAccountJoin).filter_by(account_id=account.id).first()- assert tenant_join is not None- assert tenant_join.role == "owner"-- def test_setup_failure_rollback(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test setup failure with proper rollback of all created entities.- """- fake = Faker()- admin_email = fake.email()- admin_name = fake.name()- admin_password = generate_valid_password(fake)- ip_address = fake.ipv4()- # 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-- # Mock AccountService.create_account to raise exception- with patch("services.account_service.AccountService.create_account") as mock_create_account:- mock_create_account.side_effect = Exception("Database error")-- # Execute setup and verify exception- with pytest.raises(ValueError, match="Setup failed: Database error"):- RegisterService.setup(- email=admin_email,- name=admin_name,- password=admin_password,- ip_address=ip_address,- language="en-US",- session=db_session_with_containers,- )-- # Verify no entities were created (rollback worked)- from models import Account, Tenant, TenantAccountJoin- from models.model import DifySetup-- account = db_session_with_containers.query(Account).filter_by(email=admin_email).first()- tenant_count = db_session_with_containers.query(Tenant).count()- tenant_join_count = db_session_with_containers.query(TenantAccountJoin).count()- dify_setup_count = db_session_with_containers.query(DifySetup).count()-- assert account is None- assert tenant_count == 0- assert tenant_join_count == 0- assert dify_setup_count == 0-- def test_register_success(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test successful account registration with workspace creation.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- language = fake.random_element(elements=("en-US", "zh-CN"))- # Setup mocks- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True- mock_external_service_dependencies[- "feature_service"- ].get_license.return_value.workspaces.is_available.return_value = True- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- # Execute registration- account = RegisterService.register(- email=email,- name=name,- password=password,- language=language,- session=db_session_with_containers,- )-- # Verify account was created- assert account.email == email- assert account.name == name- assert account.status == "active"- assert account.initialized_at is not None-- # Verify tenant was created and linked- from models.account import TenantAccountJoin-- tenant_join = db_session_with_containers.query(TenantAccountJoin).filter_by(account_id=account.id).first()- assert tenant_join is not None- assert tenant_join.role == "owner"- assert account.current_tenant is not None- assert account.current_tenant.name == f"{name}'s Workspace"-- def test_register_with_pending_status(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test account registration with pending status.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- language = fake.random_element(elements=("en-US", "zh-CN"))- # Setup mocks- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True- mock_external_service_dependencies[- "feature_service"- ].get_license.return_value.workspaces.is_available.return_value = True- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- # Execute registration with pending status- from models import AccountStatus-- account = RegisterService.register(- email=email,- name=name,- password=password,- language=language,- status=AccountStatus.PENDING,- session=db_session_with_containers,- )-- # Verify account was created with pending status- assert account.email == email- assert account.name == name- assert account.status == "pending"- assert account.initialized_at is not None-- # Verify tenant was created and linked- from models.account import TenantAccountJoin-- tenant_join = db_session_with_containers.query(TenantAccountJoin).filter_by(account_id=account.id).first()- assert tenant_join is not None- assert tenant_join.role == "owner"-- def test_register_workspace_creation_disabled(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test account registration when workspace creation is disabled.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- language = fake.random_element(elements=("en-US", "zh-CN"))- # Setup mocks- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = False- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- # with pytest.raises(AccountRegisterError, match="Workspace is not allowed to create."):- account = RegisterService.register(- email=email,- name=name,- password=password,- language=language,- session=db_session_with_containers,- )-- # Verify account was created with no tenant- assert account.email == email- assert account.name == name- assert account.status == "active"- assert account.initialized_at is not None-- # Verify tenant was created and linked- from models.account import TenantAccountJoin-- tenant_join = db_session_with_containers.query(TenantAccountJoin).filter_by(account_id=account.id).first()- assert tenant_join is None-- def test_register_workspace_limit_exceeded(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test account registration when workspace limit is exceeded.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- language = fake.random_element(elements=("en-US", "zh-CN"))- # Setup mocks- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True- mock_external_service_dependencies[- "feature_service"- ].get_license.return_value.workspaces.is_available.return_value = False- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- # with pytest.raises(AccountRegisterError, match="Workspace is not allowed to create."):- account = RegisterService.register(- email=email,- name=name,- password=password,- language=language,- session=db_session_with_containers,- )-- # Verify account was created with no tenant- assert account.email == email- assert account.name == name- assert account.status == "active"- assert account.initialized_at is not None-- # Verify tenant was created and linked- from models.account import TenantAccountJoin-- tenant_join = db_session_with_containers.query(TenantAccountJoin).filter_by(account_id=account.id).first()- assert tenant_join is None-- def test_register_without_workspace(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test account registration without workspace creation.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- language = fake.random_element(elements=("en-US", "zh-CN"))- # 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-- # Execute registration without workspace creation- account = RegisterService.register(- email=email,- name=name,- password=password,- language=language,- create_workspace_required=False,- session=db_session_with_containers,- )-- # Verify account was created- assert account.email == email- assert account.name == name- assert account.status == "active"- assert account.initialized_at is not None-- # Verify no tenant was created- from models.account import TenantAccountJoin-- tenant_join = db_session_with_containers.query(TenantAccountJoin).filter_by(account_id=account.id).first()- assert tenant_join is None-- def test_invite_new_member_new_account(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test inviting a new member who doesn't have an account yet.- """- fake = Faker()- tenant_name = fake.company()- inviter_email = fake.email()- inviter_name = fake.name()- inviter_password = generate_valid_password(fake)- new_member_email = fake.email()- language = fake.random_element(elements=("en-US", "zh-CN"))- # Setup mocks- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True- mock_external_service_dependencies[- "feature_service"- ].get_license.return_value.workspaces.is_available.return_value = True- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- # Create tenant and inviter account- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- inviter = AccountService.create_account(- email=inviter_email,- name=inviter_name,- interface_language="en-US",- password=inviter_password,- session=db_session_with_containers,- )- TenantService.create_tenant_member(tenant, inviter, db_session_with_containers, role="owner")-- # Mock the email task- with patch("services.account_service.send_invite_member_mail_task") as mock_send_mail:- mock_send_mail.delay.return_value = None-- # Execute invitation- token = RegisterService.invite_new_member(- tenant=tenant,- email=new_member_email,- language=language,- role="normal",- inviter=inviter,- session=db_session_with_containers,- )-- # Verify token was generated- assert token is not None- assert len(token) > 0-- # Verify email task was called- mock_send_mail.delay.assert_called_once()-- # Verify new account was created with pending status- from models import Account, TenantAccountJoin-- new_account = db_session_with_containers.query(Account).filter_by(email=new_member_email).first()- assert new_account is not None- assert new_account.name == new_member_email.split("@")[0] # Default name from email- assert new_account.status == "pending"-- # Verify tenant member was created- tenant_join = (- db_session_with_containers.query(TenantAccountJoin)- .filter_by(tenant_id=tenant.id, account_id=new_account.id)- .first()- )- assert tenant_join is not None- assert tenant_join.role == "normal"-- def test_invite_new_member_existing_account(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test inviting an existing active account who is not in the tenant yet.- """- fake = Faker()- tenant_name = fake.company()- inviter_email = fake.email()- inviter_name = fake.name()- inviter_password = generate_valid_password(fake)- existing_member_email = fake.email()- existing_member_name = fake.name()- existing_member_password = generate_valid_password(fake)- language = fake.random_element(elements=("en-US", "zh-CN"))- # 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 tenant and inviter account- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- inviter = AccountService.create_account(- email=inviter_email,- name=inviter_name,- interface_language="en-US",- password=inviter_password,- session=db_session_with_containers,- )- TenantService.create_tenant_member(tenant, inviter, db_session_with_containers, role="owner")-- # Create existing account- existing_account = AccountService.create_account(- email=existing_member_email,- name=existing_member_name,- interface_language="en-US",- password=existing_member_password,- session=db_session_with_containers,- )-- # Mock the email task- with patch("services.account_service.send_invite_member_mail_task") as mock_send_mail:- mock_send_mail.delay.return_value = None-- token = RegisterService.invite_new_member(- tenant=tenant,- email=existing_member_email,- language=language,- role="admin",- inviter=inviter,- session=db_session_with_containers,- )-- assert token is not None- assert len(token) > 0- mock_send_mail.delay.assert_called_once()-- # Existing active accounts must accept the invite before becoming workspace members.- from models.account import TenantAccountJoin-- tenant_join = (- db_session_with_containers.query(TenantAccountJoin)- .filter_by(tenant_id=tenant.id, account_id=existing_account.id)- .first()- )- assert tenant_join is None-- invitation = RegisterService.get_invitation_if_token_valid(- None, None, token, session=db_session_with_containers- )- assert invitation is not None- assert invitation["account"].id == existing_account.id- assert invitation["data"]["role"] == "admin"- assert invitation["data"]["requires_setup"] is False-- def test_invite_new_member_existing_member(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test inviting a member who is already in the tenant with pending status.- """- fake = Faker()- tenant_name = fake.company()- inviter_email = fake.email()- inviter_name = fake.name()- inviter_password = generate_valid_password(fake)- existing_pending_member_email = fake.email()- existing_pending_member_name = fake.name()- existing_pending_member_password = generate_valid_password(fake)- language = fake.random_element(elements=("en-US", "zh-CN"))- # 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 tenant and inviter account- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- inviter = AccountService.create_account(- email=inviter_email,- name=inviter_name,- interface_language="en-US",- password=inviter_password,- session=db_session_with_containers,- )- TenantService.create_tenant_member(tenant, inviter, db_session_with_containers, role="owner")-- # Create existing account with pending status- existing_account = AccountService.create_account(- email=existing_pending_member_email,- name=existing_pending_member_name,- interface_language="en-US",- password=existing_pending_member_password,- session=db_session_with_containers,- )- existing_account.status = AccountStatus.PENDING-- db_session_with_containers.commit()-- # Add existing account to tenant- TenantService.create_tenant_member(tenant, existing_account, db_session_with_containers, role="normal")-- # Mock the email task- with patch("services.account_service.send_invite_member_mail_task") as mock_send_mail:- mock_send_mail.delay.return_value = None-- # Execute invitation (should resend email for pending member)- token = RegisterService.invite_new_member(- tenant=tenant,- email=existing_pending_member_email,- language=language,- role="normal",- inviter=inviter,- session=db_session_with_containers,- )-- # Verify token was generated- assert token is not None- assert len(token) > 0-- # Verify email task was called- mock_send_mail.delay.assert_called_once()-- def test_invite_new_member_no_inviter(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test inviting a member without providing an inviter.- """- fake = Faker()- tenant_name = fake.company()- new_member_email = fake.email()- language = fake.random_element(elements=("en-US", "zh-CN"))- # 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 tenant- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)-- # Execute invitation without inviter (should fail)- with pytest.raises(ValueError, match="Inviter is required"):- RegisterService.invite_new_member(- tenant=tenant,- email=new_member_email,- language=language,- role="normal",- inviter=None,- session=db_session_with_containers,- )-- def test_invite_new_member_account_already_in_tenant(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test inviting a member who is already in the tenant with active status.- """- fake = Faker()- tenant_name = fake.company()- inviter_email = fake.email()- inviter_name = fake.name()- inviter_password = generate_valid_password(fake)- already_in_tenant_email = fake.email()- already_in_tenant_name = fake.name()- already_in_tenant_password = generate_valid_password(fake)- language = fake.random_element(elements=("en-US", "zh-CN"))- # 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 tenant and inviter account- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- inviter = AccountService.create_account(- email=inviter_email,- name=inviter_name,- interface_language="en-US",- password=inviter_password,- session=db_session_with_containers,- )- TenantService.create_tenant_member(tenant, inviter, db_session_with_containers, role="owner")-- # Create existing account with active status- existing_account = AccountService.create_account(- email=already_in_tenant_email,- name=already_in_tenant_name,- interface_language="en-US",- password=already_in_tenant_password,- session=db_session_with_containers,- )- existing_account.status = AccountStatus.ACTIVE-- db_session_with_containers.commit()-- # Add existing account to tenant- TenantService.create_tenant_member(tenant, existing_account, db_session_with_containers, role="normal")-- # Execute invitation (should fail for active member)- with pytest.raises(AccountAlreadyInTenantError, match="Account already in tenant."):- RegisterService.invite_new_member(- tenant=tenant,- email=already_in_tenant_email,- language=language,- role="normal",- inviter=inviter,- session=db_session_with_containers,- )-- def test_generate_invite_token_success(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test successful generation of invite token.- """- fake = Faker()- tenant_name = fake.company()- 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 tenant and account- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- # Execute token generation- token = RegisterService.generate_invite_token(tenant, account)-- # Verify token was generated- assert token is not None- assert len(token) > 0-- # Verify token was stored in Redis- from extensions.ext_redis import redis_client-- token_key = RegisterService._get_invitation_token_key(token)- stored_data = redis_client.get(token_key)- assert stored_data is not None-- # Verify stored data contains correct information- import json-- invitation_data = json.loads(stored_data.decode("utf-8"))- assert invitation_data["account_id"] == str(account.id)- assert invitation_data["email"] == account.email- assert invitation_data["workspace_id"] == tenant.id-- def test_revoke_token_with_workspace_and_email(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test revoking token with workspace ID and email.- """- fake = Faker()- tenant_name = fake.company()- 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 tenant and account- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- # Generate a real token- token = RegisterService.generate_invite_token(tenant, account)-- # Verify token exists in Redis before revocation- from extensions.ext_redis import redis_client-- token_key = RegisterService._get_invitation_token_key(token)- assert redis_client.get(token_key) is not None-- # Execute token revocation- RegisterService.revoke_token(- workspace_id=tenant.id,- email=account.email,- token=token,- )-- # Verify token was not deleted from Redis- assert redis_client.get(token_key) is not None-- def test_revoke_token_without_workspace_and_email(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test revoking token without workspace ID and email.- """- fake = Faker()- tenant_name = fake.company()- 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 tenant and account- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )-- # Generate a real token- token = RegisterService.generate_invite_token(tenant, account)-- # Verify token exists in Redis before revocation- from extensions.ext_redis import redis_client-- token_key = RegisterService._get_invitation_token_key(token)- assert redis_client.get(token_key) is not None-- # Execute token revocation without workspace and email- RegisterService.revoke_token(- workspace_id="",- email="",- token=token,- )-- # Verify token was deleted from Redis- assert redis_client.get(token_key) is None-- def test_get_invitation_if_token_valid_success(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test getting invitation data with valid token.- """- fake = Faker()- tenant_name = fake.company()- 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 tenant and account- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )- TenantService.create_tenant_member(tenant, account, db_session_with_containers, role="normal")-- # Generate a real token- token = RegisterService.generate_invite_token(tenant, account)-- email_hash = sha256(account.email.encode()).hexdigest()- cache_key = f"member_invite_token:{tenant.id}, {email_hash}:{token}"- from extensions.ext_redis import redis_client-- redis_client.setex(cache_key, 24 * 60 * 60, account.id)-- # Execute invitation retrieval- result = RegisterService.get_invitation_if_token_valid(- workspace_id=tenant.id,- email=account.email,- token=token,- session=db_session_with_containers,- )-- # Verify result contains expected data- assert result is not None- assert result["account"].id == account.id- assert result["tenant"].id == tenant.id- assert result["data"]["account_id"] == str(account.id)- assert result["data"]["email"] == account.email- assert result["data"]["workspace_id"] == tenant.id-- def test_get_invitation_if_token_valid_invalid_token(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test getting invitation data with invalid token.- """- fake = Faker()- workspace_id = fake.uuid4()- email = fake.email()- invalid_token = fake.uuid4()- # Execute invitation retrieval with invalid token- result = RegisterService.get_invitation_if_token_valid(- workspace_id=workspace_id,- email=email,- token=invalid_token,- session=db_session_with_containers,- )-- # Verify result is None- assert result is None-- def test_get_invitation_if_token_valid_invalid_tenant(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test getting invitation data with invalid tenant.- """- fake = Faker()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- invalid_tenant_id = fake.uuid4()- token = fake.uuid4()- # 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,- )-- # Create a real token but with non-existent tenant ID- from extensions.ext_redis import redis_client-- invitation_data = {- "account_id": str(account.id),- "email": account.email,- "workspace_id": invalid_tenant_id,- }- token_key = RegisterService._get_invitation_token_key(token)- import json-- redis_client.setex(token_key, 24 * 60 * 60, json.dumps(invitation_data))-- # Execute invitation retrieval- result = RegisterService.get_invitation_if_token_valid(- workspace_id=invalid_tenant_id,- email=account.email,- token=token,- session=db_session_with_containers,- )-- # Verify result is None (tenant not found)- assert result is None-- # Clean up- redis_client.delete(token_key)-- def test_get_invitation_if_token_valid_account_mismatch(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test getting invitation data with account ID mismatch.- """- fake = Faker()- tenant_name = fake.company()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- token = fake.uuid4()- # 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 tenant and account- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )- TenantService.create_tenant_member(tenant, account, db_session_with_containers, role="normal")-- # Create a real token but with mismatched account ID- from extensions.ext_redis import redis_client-- invitation_data = {- "account_id": "different-account-id", # Different from actual account ID- "email": account.email,- "workspace_id": tenant.id,- }- token_key = RegisterService._get_invitation_token_key(token)- redis_client.setex(token_key, 24 * 60 * 60, json.dumps(invitation_data))-- # Execute invitation retrieval- result = RegisterService.get_invitation_if_token_valid(- workspace_id=tenant.id,- email=account.email,- token=token,- session=db_session_with_containers,- )-- # Verify result is None (account ID mismatch)- assert result is None-- # Clean up- redis_client.delete(token_key)-- def test_get_invitation_if_token_valid_tenant_not_normal(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test getting invitation data with tenant not in normal status.- """- fake = Faker()- tenant_name = fake.company()- email = fake.email()- name = fake.name()- password = generate_valid_password(fake)- token = fake.uuid4()- # 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 tenant and account- tenant = TenantService.create_tenant(name=tenant_name, session=db_session_with_containers)- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=password,- session=db_session_with_containers,- )- TenantService.create_tenant_member(tenant, account, db_session_with_containers, role="normal")-- # Change tenant status to non-normal- tenant.status = TenantStatus.ARCHIVE-- db_session_with_containers.commit()-- # Create a real token- from extensions.ext_redis import redis_client-- invitation_data = {- "account_id": str(account.id),- "email": account.email,- "workspace_id": tenant.id,- }- token_key = RegisterService._get_invitation_token_key(token)- import json-- redis_client.setex(token_key, 24 * 60 * 60, json.dumps(invitation_data))-- # Execute invitation retrieval- result = RegisterService.get_invitation_if_token_valid(- workspace_id=tenant.id,- email=account.email,- token=token,- session=db_session_with_containers,- )-- # Verify result is None (tenant not in normal status)- assert result is None-- # Clean up- redis_client.delete(token_key)-- def test_get_invitation_by_token_with_workspace_and_email(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test getting invitation by token with workspace ID and email.- """- fake = Faker()- token = fake.uuid4()- workspace_id = fake.uuid4()- email = fake.email()-- # Create the cache key as the service does- from hashlib import sha256-- from extensions.ext_redis import redis_client-- email_hash = sha256(email.encode()).hexdigest()- cache_key = f"member_invite_token:{workspace_id}, {email_hash}:{token}"-- # Store account ID in Redis- account_id = fake.uuid4()- redis_client.setex(cache_key, 24 * 60 * 60, account_id)-- # Execute invitation retrieval- result = RegisterService.get_invitation_by_token(- token=token,- workspace_id=workspace_id,- email=email,- )-- # Verify result contains expected data- assert result is not None- assert result["account_id"] == account_id- assert result["email"] == email- assert result["workspace_id"] == workspace_id-- # Clean up- redis_client.delete(cache_key)-- def test_get_invitation_by_token_without_workspace_and_email(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test getting invitation by token without workspace ID and email.- """- fake = Faker()- token = fake.uuid4()- invitation_data = {- "account_id": fake.uuid4(),- "email": fake.email(),- "workspace_id": fake.uuid4(),- }-- # Store invitation data in Redis using standard token key- from extensions.ext_redis import redis_client-- token_key = RegisterService._get_invitation_token_key(token)- import json-- redis_client.setex(token_key, 24 * 60 * 60, json.dumps(invitation_data))-- # Execute invitation retrieval- result = RegisterService.get_invitation_by_token(token=token)-- # Verify result contains expected data- assert result is not None- assert result["account_id"] == invitation_data["account_id"]- assert result["email"] == invitation_data["email"]- assert result["workspace_id"] == invitation_data["workspace_id"]-- # Clean up- redis_client.delete(token_key)-- def test_get_invitation_token_key(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test getting invitation token key.- """- fake = Faker()- token = fake.uuid4()- # Execute token key generation- token_key = RegisterService._get_invitation_token_key(token)-- # Verify token key format- assert token_key == f"member_invite:token:{token}"diff --git a/api/tests/test_containers_integration_tests/services/test_agent_service.py b/api/tests/test_containers_integration_tests/services/test_agent_service.pyindex 4217e573b5a..ab7c658be08 100644--- a/api/tests/test_containers_integration_tests/services/test_agent_service.py+++ b/api/tests/test_containers_integration_tests/services/test_agent_service.py@@ -9,9 +9,9 @@ from core.plugin.impl.exc import PluginDaemonClientSideErrorfrom models import Account, AppMode, CreatorUserRolefrom models.enums import ConversationFromSource, EndUserType, MessageFileBelongsTofrom models.model import AppModelConfig, Conversation, EndUser, Message, MessageAgentThought-from services.account_service import AccountService, TenantServicefrom services.agent_service import AgentServicefrom services.app_service import AppService, CreateAppParams+from tests.test_containers_integration_tests.helpers import accounts as account_fixturesfrom tests.test_containers_integration_tests.helpers import generate_valid_password@@ -29,7 +29,9 @@ class TestAgentService:patch("services.app_service.SystemFeatureService", autospec=True) as mock_feature_service,patch("services.app_service.EnterpriseService", autospec=True) as mock_enterprise_service,patch("services.app_service.ModelManager.for_tenant", autospec=True) as mock_model_manager,- patch("services.account_service.SystemFeatureService", autospec=True) as mock_account_feature_service,+ patch(+ "services.account.login_adapters.SystemFeatureService", autospec=True+ ) as mock_account_feature_service,):# Setup default mock returns for agent servicemock_plugin_agent_client_instance = mock_plugin_agent_client.return_value@@ -107,14 +109,14 @@ class TestAgentService:mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenant- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create app with realistic datadiff --git a/api/tests/test_containers_integration_tests/services/test_annotation_service.py b/api/tests/test_containers_integration_tests/services/test_annotation_service.pyindex d5ba5b20d68..ddf1fe25c97 100644--- a/api/tests/test_containers_integration_tests/services/test_annotation_service.py+++ b/api/tests/test_containers_integration_tests/services/test_annotation_service.py@@ -23,7 +23,7 @@ class TestAnnotationService:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.account_service.SystemFeatureService") as mock_account_feature_service,+ patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service,patch("services.annotation_service.FeatureService") as mock_feature_service,patch("services.annotation_service.add_annotation_to_index_task") as mock_add_task,patch("services.annotation_service.update_annotation_to_index_task") as mock_update_task,@@ -74,16 +74,16 @@ class TestAnnotationService:mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenant first- from services.account_service import AccountService, TenantService+ from tests.test_containers_integration_tests.helpers import accounts as account_fixtures- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Setup app creation argumentsdiff --git a/api/tests/test_containers_integration_tests/services/test_api_based_extension_service.py b/api/tests/test_containers_integration_tests/services/test_api_based_extension_service.pyindex 1312911df1a..ed813d62879 100644--- a/api/tests/test_containers_integration_tests/services/test_api_based_extension_service.py+++ b/api/tests/test_containers_integration_tests/services/test_api_based_extension_service.py@@ -5,8 +5,8 @@ from faker import Fakerfrom sqlalchemy.orm import Sessionfrom models.api_based_extension import APIBasedExtension-from services.account_service import AccountService, TenantServicefrom services.api_based_extension_service import APIBasedExtensionService+from tests.test_containers_integration_tests.helpers import accounts as account_fixturesfrom tests.test_containers_integration_tests.helpers import generate_valid_password@@ -17,7 +17,7 @@ class TestAPIBasedExtensionService:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.account_service.SystemFeatureService") as mock_account_feature_service,+ patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service,patch("services.api_based_extension_service.APIBasedExtensionRequestor") as mock_requestor,):# Mock successful ping response@@ -47,14 +47,14 @@ class TestAPIBasedExtensionService:mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenant- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantreturn account, tenantdiff --git a/api/tests/test_containers_integration_tests/services/test_app_dsl_service.py b/api/tests/test_containers_integration_tests/services/test_app_dsl_service.pyindex bc93c0f4a29..786d0659370 100644--- a/api/tests/test_containers_integration_tests/services/test_app_dsl_service.py+++ b/api/tests/test_containers_integration_tests/services/test_app_dsl_service.py@@ -38,7 +38,6 @@ from models.agent_config_entities import AgentSoulConfigfrom models.model import AppModelConfig, IconTypefrom models.workflow import Workflow, WorkflowTypefrom services import app_dsl_service-from services.account_service import AccountService, TenantServicefrom services.agent.dsl_entities import AGENT_PACKAGE_REF_KEY, make_portable_agent_packagefrom services.agent.dsl_service import AgentDslServicefrom services.app_creation_records import create_site_record@@ -57,6 +56,7 @@ from services.app_dsl_service import (from services.app_service import AppService, CreateAppParamsfrom services.dsl_version import check_version_compatibilityfrom services.errors.app import WorkflowNotFoundError+from tests.test_containers_integration_tests.helpers import accounts as account_fixturesfrom tests.test_containers_integration_tests.helpers import generate_valid_password_DEFAULT_TENANT_ID = "00000000-0000-0000-0000-000000000001"@@ -153,18 +153,16 @@ class TestAppDslService:def _create_test_app_and_account(self, db_session_with_containers: Session, mock_external_service_dependencies):fake = Faker()- with patch("services.account_service.SystemFeatureService") as mock_account_feature_service:+ with patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service:mock_account_feature_service.is_registration_allowed.return_value = True- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(- account, name=fake.company(), session=db_session_with_containers- )+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantapp_args = CreateAppParams(name=fake.company(),diff --git a/api/tests/test_containers_integration_tests/services/test_app_generate_service.py b/api/tests/test_containers_integration_tests/services/test_app_generate_service.pyindex d19b134d687..a7eec53a182 100644--- a/api/tests/test_containers_integration_tests/services/test_app_generate_service.py+++ b/api/tests/test_containers_integration_tests/services/test_app_generate_service.py@@ -39,7 +39,9 @@ class TestAppGenerateService:patch("services.app_generate_service.MessageBasedAppGenerator", autospec=True) as mock_message_based_generator,- patch("services.account_service.SystemFeatureService", autospec=True) as mock_account_feature_service,+ patch(+ "services.account.login_adapters.SystemFeatureService", autospec=True+ ) as mock_account_feature_service,patch("services.app_generate_service.dify_config") as mock_dify_config,patch("services.quota_service.dify_config") as mock_quota_dify_config,patch("configs.dify_config") as mock_global_dify_config,@@ -166,16 +168,16 @@ class TestAppGenerateService:mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenant- from services.account_service import AccountService, TenantService+ from tests.test_containers_integration_tests.helpers import accounts as account_fixtures- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantfrom services.app_service import AppService, CreateAppParamsdiff --git a/api/tests/test_containers_integration_tests/services/test_app_service.py b/api/tests/test_containers_integration_tests/services/test_app_service.pyindex a71371b95d8..72cb9314a44 100644--- a/api/tests/test_containers_integration_tests/services/test_app_service.py+++ b/api/tests/test_containers_integration_tests/services/test_app_service.py@@ -11,7 +11,7 @@ from constants.model_template import default_app_templatesfrom models import Accountfrom models.model import App, IconTypefrom repositories.app.console_repository import ConsoleAppRepository-from services.account_service import AccountService, TenantService+from tests.test_containers_integration_tests.helpers import accounts as account_fixturesfrom tests.test_containers_integration_tests.helpers import generate_valid_password# Delay import of AppService to avoid circular dependency@@ -28,7 +28,7 @@ class TestAppService:patch("services.app_service.SystemFeatureService") as mock_feature_service,patch("services.app_service.EnterpriseService") as mock_enterprise_service,patch("services.app_service.ModelManager.for_tenant") as mock_model_manager,- patch("services.account_service.SystemFeatureService") as mock_account_feature_service,+ patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service,):# Setup default mock returns for app servicemock_feature_service.is_webapp_auth_enabled.return_value = False@@ -56,14 +56,14 @@ class TestAppService:fake = Faker()# Create account and tenant first- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Setup app creation arguments@@ -114,14 +114,14 @@ class TestAppService:fake = Faker()# Create account and tenant first- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Import here to avoid circular dependency@@ -158,14 +158,14 @@ class TestAppService:fake = Faker()# Create account and tenant first- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Import here to avoid circular dependency@@ -210,14 +210,14 @@ class TestAppService:"""fake = Faker()- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantfrom services.app_service import AppListParams, AppService, CreateAppParams@@ -297,14 +297,14 @@ class TestAppService:"""fake = Faker()- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantfrom models import AppStar@@ -360,14 +360,14 @@ class TestAppService:"""fake = Faker()- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantfrom services.app_service import AppService, CreateAppParams@@ -464,14 +464,14 @@ class TestAppService:fake = Faker()# Create account and tenant first- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Import here to avoid circular dependency@@ -533,18 +533,16 @@ class TestAppService:"""fake = Faker()- first_account = AccountService.create_account(+ first_account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(- first_account, name=fake.company(), session=db_session_with_containers- )+ account_fixtures.create_owner_workspace(first_account, name=fake.company(), session=db_session_with_containers)tenant = first_account.current_tenant- second_account = AccountService.create_account(+ second_account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",@@ -594,14 +592,14 @@ class TestAppService:fake = Faker()# Create account and tenant first- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Import here to avoid circular dependency@@ -657,14 +655,14 @@ class TestAppService:fake = Faker()# Create account and tenant first- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create app first@@ -728,14 +726,14 @@ class TestAppService:"""fake = Faker()- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantfrom services.app_service import AppService, CreateAppParams@@ -783,14 +781,14 @@ class TestAppService:"""fake = Faker()- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantfrom services.app_service import AppService, CreateAppParams@@ -838,14 +836,14 @@ class TestAppService:fake = Faker()# Create account and tenant first- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create app first@@ -896,14 +894,14 @@ class TestAppService:fake = Faker()# Create account and tenant first- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create app first@@ -948,14 +946,14 @@ class TestAppService:fake = Faker()# Create account and tenant first- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create app first@@ -1006,14 +1004,14 @@ class TestAppService:fake = Faker()# Create account and tenant first- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)# Import here to avoid circular dependencyfrom services.app_service import CreateAppParams@@ -1043,14 +1041,14 @@ class TestAppService:fake = Faker()# Create account and tenant first- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Import here to avoid circular dependencydiff --git a/api/tests/test_containers_integration_tests/services/test_credit_pool_service.py b/api/tests/test_containers_integration_tests/services/test_credit_pool_service.pyindex 9cbe5252bbf..020e731fa30 100644--- a/api/tests/test_containers_integration_tests/services/test_credit_pool_service.py+++ b/api/tests/test_containers_integration_tests/services/test_credit_pool_service.py@@ -33,17 +33,6 @@ class TestCreditPoolService:db_session.add(pool)db_session.commit()- def test_create_default_pool(self, db_session_with_containers: Session) -> None:- tenant_id = self._create_tenant_id()-- pool = CreditPoolService.create_default_pool(tenant_id, session=db_session_with_containers)-- assert isinstance(pool, TenantCreditPool)- assert pool.tenant_id == tenant_id- assert pool.pool_type == ProviderQuotaType.TRIAL- assert pool.quota_used == 0- assert pool.quota_limit > 0-def test_get_pool_returns_pool_when_exists(self, db_session_with_containers: Session) -> None:tenant_id = self._create_tenant_id()self._create_pool(db_session_with_containers, tenant_id=tenant_id, quota_limit=10, quota_used=0)diff --git a/api/tests/test_containers_integration_tests/services/test_dataset_permission_service.py b/api/tests/test_containers_integration_tests/services/test_dataset_permission_service.pyindex 4285108c054..505fc29df66 100644--- a/api/tests/test_containers_integration_tests/services/test_dataset_permission_service.py+++ b/api/tests/test_containers_integration_tests/services/test_dataset_permission_service.py@@ -19,7 +19,7 @@ from models.dataset import (DatasetPermissionEnum,)from models.enums import DataSourceType-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.knowledge.dataset_service import DatasetPermissionService, DatasetServicediff --git a/api/tests/test_containers_integration_tests/services/test_dataset_service_document.py b/api/tests/test_containers_integration_tests/services/test_dataset_service_document.pyindex 28dc5d2f583..e221eaf4be3 100644--- a/api/tests/test_containers_integration_tests/services/test_dataset_service_document.py+++ b/api/tests/test_containers_integration_tests/services/test_dataset_service_document.py@@ -17,7 +17,7 @@ from models.dataset import Dataset, Documentfrom models.enums import CreatorUserRole, DataSourceType, DocumentCreatedFrom, IndexingStatusfrom models.model import UploadFilefrom repositories.knowledge.dataset_read_repository import get_dataset_doc_form-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.knowledge.dataset_service import DocumentServicefrom services.knowledge.resource_scope import DatasetRefdiff --git a/api/tests/test_containers_integration_tests/services/test_dataset_service_permissions.py b/api/tests/test_containers_integration_tests/services/test_dataset_service_permissions.pyindex 9c7e2d48269..194bca1d8a7 100644--- a/api/tests/test_containers_integration_tests/services/test_dataset_service_permissions.py+++ b/api/tests/test_containers_integration_tests/services/test_dataset_service_permissions.py@@ -21,7 +21,7 @@ from models.dataset import (DatasetPermissionEnum,)from models.enums import DataSourceType-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.knowledge.dataset_service import DatasetCollectionBindingService, DatasetPermissionService, DatasetServicefrom services.knowledge.resource_scope import DatasetReffrom tests.unit_tests.config_override import config_overrides_contextdiff --git a/api/tests/test_containers_integration_tests/services/test_dataset_service_update_dataset.py b/api/tests/test_containers_integration_tests/services/test_dataset_service_update_dataset.pyindex cfa8b74d466..ebf6fa0f54d 100644--- a/api/tests/test_containers_integration_tests/services/test_dataset_service_update_dataset.py+++ b/api/tests/test_containers_integration_tests/services/test_dataset_service_update_dataset.py@@ -17,7 +17,7 @@ from models.account import ()from models.dataset import Dataset, ExternalKnowledgeApis, ExternalKnowledgeBindingsfrom models.enums import DataSourceType-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.knowledge.dataset_service import DatasetServicediff --git a/api/tests/test_containers_integration_tests/services/test_message_service.py b/api/tests/test_containers_integration_tests/services/test_message_service.pyindex 8c935876fe2..32456f02698 100644--- a/api/tests/test_containers_integration_tests/services/test_message_service.py+++ b/api/tests/test_containers_integration_tests/services/test_message_service.py@@ -24,7 +24,7 @@ class TestMessageService:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.account_service.SystemFeatureService") as mock_account_feature_service,+ patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service,patch("services.message_service.ModelManager.for_tenant") as mock_model_manager,patch("services.message_service.WorkflowService") as mock_workflow_service,patch("services.message_service.AdvancedChatAppConfigManager") as mock_app_config_manager,@@ -88,16 +88,16 @@ class TestMessageService:mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenant first- from services.account_service import AccountService, TenantService+ from tests.test_containers_integration_tests.helpers import accounts as account_fixtures- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Setup app creation arguments@@ -699,18 +699,16 @@ class TestMessageService:message = self._create_test_message(db_session_with_containers, app, conversation, account, fake)# Create another account- from services.account_service import AccountService, TenantService+ from tests.test_containers_integration_tests.helpers import accounts as account_fixtures- other_account = AccountService.create_account(+ other_account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(- other_account, name=fake.company(), session=db_session_with_containers- )+ account_fixtures.create_owner_workspace(other_account, name=fake.company(), session=db_session_with_containers)# Test getting message with different userwith pytest.raises(MessageNotExistsError):diff --git a/api/tests/test_containers_integration_tests/services/test_schedule_service.py b/api/tests/test_containers_integration_tests/services/test_schedule_service.pyindex 3eb55e5fe2a..aeab080a6a2 100644--- a/api/tests/test_containers_integration_tests/services/test_schedule_service.py+++ b/api/tests/test_containers_integration_tests/services/test_schedule_service.py@@ -13,7 +13,7 @@ from core.workflow.nodes.trigger_schedule.exc import ScheduleNotFoundErrorfrom events.event_handlers.sync_workflow_schedule_when_app_published import sync_schedule_from_workflowfrom models.account import Account, Tenant, TenantAccountJoin, TenantAccountRolefrom models.trigger import WorkflowSchedulePlan-from services.errors.account import AccountNotFoundError+from services.account_errors import AccountNotFoundErrorfrom services.trigger.schedule_service import ScheduleServicediff --git a/api/tests/test_containers_integration_tests/services/test_trigger_provider_service.py b/api/tests/test_containers_integration_tests/services/test_trigger_provider_service.pyindex 90160d5a963..8934ed1dbf6 100644--- a/api/tests/test_containers_integration_tests/services/test_trigger_provider_service.py+++ b/api/tests/test_containers_integration_tests/services/test_trigger_provider_service.py@@ -27,7 +27,7 @@ class TestTriggerProviderService:patch("services.trigger.trigger_provider_service.TriggerManager") as mock_trigger_manager,patch("services.trigger.trigger_provider_service.redis_client") as mock_redis_client,patch("services.trigger.trigger_provider_service.delete_cache_for_subscription") as mock_delete_cache,- patch("services.account_service.SystemFeatureService") as mock_account_feature_service,+ patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service,):# Setup default mock returnsmock_provider_controller = MagicMock()@@ -68,7 +68,7 @@ class TestTriggerProviderService:"""fake = Faker()- from services.account_service import AccountService, TenantService+ from tests.test_containers_integration_tests.helpers import accounts as account_fixtures# Setup mocks for account creationmock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True@@ -77,14 +77,14 @@ class TestTriggerProviderService:].get_trigger_provider.return_value = mock_external_service_dependencies["provider_controller"]# Create account and tenant- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantassert tenant is not Nonediff --git a/api/tests/test_containers_integration_tests/services/test_web_conversation_service.py b/api/tests/test_containers_integration_tests/services/test_web_conversation_service.pyindex 484f093ed47..a0ece2a2eff 100644--- a/api/tests/test_containers_integration_tests/services/test_web_conversation_service.py+++ b/api/tests/test_containers_integration_tests/services/test_web_conversation_service.py@@ -10,9 +10,9 @@ from models import Account, Appfrom models.enums import ConversationFromSource, EndUserTypefrom models.model import Conversation, EndUserfrom models.web import PinnedConversation-from services.account_service import AccountService, TenantServicefrom services.app_service import AppService, CreateAppParamsfrom services.web_conversation_service import WebConversationService+from tests.test_containers_integration_tests.helpers import accounts as account_fixturesfrom tests.test_containers_integration_tests.helpers import generate_valid_password@@ -26,7 +26,7 @@ class TestWebConversationService:patch("services.app_service.SystemFeatureService") as mock_feature_service,patch("services.app_service.EnterpriseService") as mock_enterprise_service,patch("services.app_service.ModelManager.for_tenant") as mock_model_manager,- patch("services.account_service.SystemFeatureService") as mock_account_feature_service,+ patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service,):# Setup default mock returns for app servicemock_feature_service.is_webapp_auth_enabled.return_value = False@@ -65,14 +65,14 @@ class TestWebConversationService:mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenant- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create app with realistic datadiff --git a/api/tests/test_containers_integration_tests/services/test_webhook_service.py b/api/tests/test_containers_integration_tests/services/test_webhook_service.pyindex 0f67408cb03..74dbee453d4 100644--- a/api/tests/test_containers_integration_tests/services/test_webhook_service.py+++ b/api/tests/test_containers_integration_tests/services/test_webhook_service.py@@ -13,8 +13,8 @@ from models.enums import AppTriggerStatus, AppTriggerTypefrom models.model import Appfrom models.trigger import AppTrigger, WorkflowWebhookTriggerfrom models.workflow import Workflow-from services.account_service import AccountService, TenantServicefrom services.trigger.webhook_service import WebhookService+from tests.test_containers_integration_tests.helpers import accounts as account_fixturesfrom tests.test_containers_integration_tests.helpers import generate_valid_password@@ -37,21 +37,21 @@ def test_data(fake = Faker()monkeypatch.setattr(- "services.account_service.SystemFeatureService.is_registration_allowed",+ "services.account.login_adapters.SystemFeatureService.is_registration_allowed",lambda: True,)monkeypatch.setattr(- "services.account_service.SystemFeatureService.is_workspace_creation_allowed",+ "services.account.login_adapters.SystemFeatureService.is_workspace_creation_allowed",lambda: True,)- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantassert tenant is not Noneapp = App(diff --git a/api/tests/test_containers_integration_tests/services/test_workflow_app_service.py b/api/tests/test_containers_integration_tests/services/test_workflow_app_service.pyindex e31cf7d80ad..caaa7ea54c6 100644--- a/api/tests/test_containers_integration_tests/services/test_workflow_app_service.py+++ b/api/tests/test_containers_integration_tests/services/test_workflow_app_service.py@@ -14,8 +14,8 @@ from models import EndUser, Workflow, WorkflowAppLog, WorkflowRunfrom models.enums import CreatorUserRole, EndUserTypefrom models.workflow import WorkflowAppLogCreatedFromfrom repositories.workflow_app_log_query_repository import WorkflowAppLogQueryRepository-from services.account_service import AccountService, TenantServicefrom services.workflow_app_log_query_service import WorkflowAppLogQueryService+from tests.test_containers_integration_tests.helpers import accounts as account_fixturesfrom tests.test_containers_integration_tests.helpers import generate_valid_password@@ -57,7 +57,7 @@ class TestWorkflowAppLogQueryService:patch("services.app_service.SystemFeatureService") as mock_feature_service,patch("services.app_service.EnterpriseService") as mock_enterprise_service,patch("services.app_service.ModelManager.for_tenant") as mock_model_manager,- patch("services.account_service.SystemFeatureService") as mock_account_feature_service,+ patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service,):# Setup default mock returns for app servicemock_feature_service.is_webapp_auth_enabled.return_value = False@@ -96,14 +96,14 @@ class TestWorkflowAppLogQueryService:mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenant- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Import here to avoid circular dependency@@ -143,14 +143,14 @@ class TestWorkflowAppLogQueryService:mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenant- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantreturn tenant, accountdiff --git a/api/tests/test_containers_integration_tests/services/test_workflow_run_service.py b/api/tests/test_containers_integration_tests/services/test_workflow_run_service.pyindex 8d37aaa4e8c..f24cc6f772a 100644--- a/api/tests/test_containers_integration_tests/services/test_workflow_run_service.py+++ b/api/tests/test_containers_integration_tests/services/test_workflow_run_service.py@@ -16,9 +16,9 @@ from models.model import (from models.workflow import WorkflowRunfrom repositories.factory import DifyAPIRepositoryFactoryfrom repositories.sqlalchemy_api_workflow_run_repository import DifyAPISQLAlchemyWorkflowRunRepository-from services.account_service import AccountService, TenantServicefrom services.app_service import AppService, CreateAppParamsfrom services.workflow_run_service import WorkflowRunService+from tests.test_containers_integration_tests.helpers import accounts as account_fixturesfrom tests.test_containers_integration_tests.helpers import generate_valid_password@@ -45,7 +45,7 @@ class TestWorkflowRunService:patch("services.app_service.SystemFeatureService") as mock_feature_service,patch("services.app_service.EnterpriseService") as mock_enterprise_service,patch("services.app_service.ModelManager.for_tenant") as mock_model_manager,- patch("services.account_service.SystemFeatureService") as mock_account_feature_service,+ patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service,):# Setup default mock returns for app servicemock_feature_service.is_webapp_auth_enabled.return_value = False@@ -93,14 +93,14 @@ class TestWorkflowRunService:mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenant- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create app with realistic data@@ -593,19 +593,17 @@ class TestWorkflowRunService:- No errors when querying non-existent executions"""# Arrange: Setup test data- account_service = AccountService()- tenant_service = TenantService()app_service = AppService()# Create account and tenant- account = account_service.create_account(+ account = account_fixtures.create_account(email="[email protected]",name="Test User",password="password123",interface_language="en-US",session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name="test_tenant", session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name="test_tenant", session=db_session_with_containers)tenant = account.current_tenant# Create app@@ -647,19 +645,17 @@ class TestWorkflowRunService:- No errors when querying with invalid ID"""# Arrange: Setup test data- account_service = AccountService()- tenant_service = TenantService()app_service = AppService()# Create account and tenant- account = account_service.create_account(+ account = account_fixtures.create_account(email="[email protected]",name="Test User",password="password123",interface_language="en-US",session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name="test_tenant", session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name="test_tenant", session=db_session_with_containers)tenant = account.current_tenant# Create appdiff --git a/api/tests/test_containers_integration_tests/services/test_workspace_service.py b/api/tests/test_containers_integration_tests/services/test_workspace_service.pydeleted file mode 100644index 343665b856b..00000000000--- a/api/tests/test_containers_integration_tests/services/test_workspace_service.py+++ /dev/null@@ -1,823 +0,0 @@-from __future__ import annotations--import json-from unittest.mock import MagicMock, patch--import pytest-from faker import Faker-from sqlalchemy.orm import Session--from enums import CloudPlan, DeploymentEdition-from models import Account, Tenant, TenantAccountJoin, TenantAccountRole-from services.credit_pool_service import CreditPoolBalance-from services.workspace_service import WorkspaceService---class TestWorkspaceService:- """Integration tests for WorkspaceService using testcontainers."""-- @pytest.fixture- def mock_external_service_dependencies(self):- """Mock setup for external service dependencies."""- with (- patch("services.workspace_service.FeatureService") as mock_feature_service,- patch("services.workspace_service.TenantService") as mock_tenant_service,- patch("services.workspace_service.dify_config") as mock_dify_config,- ):- # Setup default mock returns- feature = mock_feature_service.get_features.return_value- feature.can_replace_logo = True- feature.billing.subscription.plan = "professional"- mock_tenant_service.has_roles.return_value = True- mock_dify_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD- mock_dify_config.FILES_URL = "https://example.com/files"-- yield {- "feature_service": mock_feature_service,- "tenant_service": mock_tenant_service,- "dify_config": mock_dify_config,- }-- def _create_test_account_and_tenant(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Helper method to create a test account and tenant for testing.-- Args:- db_session_with_containers: Database session from testcontainers infrastructure- mock_external_service_dependencies: Mock dependencies-- Returns:- tuple: (account, tenant) - Created account and tenant instances- """- fake = Faker()-- # Create account- account = Account(- email=fake.email(),- name=fake.name(),- interface_language="en-US",- status="active",- )-- db_session_with_containers.add(account)- db_session_with_containers.commit()-- # Create tenant- tenant = Tenant(- name=fake.company(),- status="normal",- plan="basic",- custom_config='{"replace_webapp_logo": true, "remove_webapp_brand": false}',- )- db_session_with_containers.add(tenant)- db_session_with_containers.commit()-- # Create tenant-account join with owner role- join = TenantAccountJoin(- tenant_id=tenant.id,- account_id=account.id,- role=TenantAccountRole.OWNER,- current=True,- )- db_session_with_containers.add(join)- db_session_with_containers.commit()-- # Set current tenant for account- account.set_current_tenant_with_session(tenant, session=db_session_with_containers)-- return account, tenant-- def test_get_tenant_info_success(self, db_session_with_containers: Session, mock_external_service_dependencies):- """- Test successful retrieval of tenant information with all features enabled.-- This test verifies:- - Proper tenant info retrieval with all required fields- - Correct role assignment from TenantAccountJoin- - Custom config handling when features are enabled- - Logo replacement functionality for privileged users- """- # Arrange: Create test data- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )-- # Setup mocks for feature service- mock_external_service_dependencies["feature_service"].get_features.return_value.can_replace_logo = True- mock_external_service_dependencies["tenant_service"].has_roles.return_value = True-- # Mock current_user for flask_login- with patch("services.workspace_service.current_user", account):- # Act: Execute the method under test- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- # Assert: Verify the expected outcomes- assert result is not None- assert result["id"] == tenant.id- assert result["name"] == tenant.name- assert result["plan"] == "professional"- assert result["status"] == tenant.status- assert result["role"] == TenantAccountRole.OWNER- assert result["created_at"] == tenant.created_at- assert result["trial_end_reason"] is None-- # Verify custom config is included for privileged users- assert "custom_config" in result- assert result["custom_config"]["remove_webapp_brand"] is False- assert "replace_webapp_logo" in result["custom_config"]-- # Verify database state-- db_session_with_containers.refresh(tenant)- assert tenant.id is not None-- def test_get_tenant_info_without_custom_config(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test tenant info retrieval when custom config features are disabled.-- This test verifies:- - Tenant info retrieval without custom config when features are disabled- - Proper handling of disabled logo replacement functionality- - Role assignment still works correctly- - Basic tenant information is complete- """- # Arrange: Create test data- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )-- # Setup mocks to disable custom config features- mock_external_service_dependencies["feature_service"].get_features.return_value.can_replace_logo = False- mock_external_service_dependencies["tenant_service"].has_roles.return_value = False-- # Mock current_user for flask_login- with patch("services.workspace_service.current_user", account):- # Act: Execute the method under test- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- # Assert: Verify the expected outcomes- assert result is not None- assert result["id"] == tenant.id- assert result["name"] == tenant.name- assert result["plan"] == "professional"- assert result["status"] == tenant.status- assert result["role"] == TenantAccountRole.OWNER- assert result["created_at"] == tenant.created_at- assert result["trial_end_reason"] is None-- # Verify custom config is not included when features are disabled- assert "custom_config" not in result-- # Verify database state-- db_session_with_containers.refresh(tenant)- assert tenant.id is not None-- def test_get_tenant_info_with_normal_user_role(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test tenant info retrieval for normal user role without privileged features.-- This test verifies:- - Tenant info retrieval for non-privileged users- - Role assignment for normal users- - Custom config is not accessible for normal users- - Proper handling of different user roles- """- # Arrange: Create test data- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )-- # Update the join to have normal role-- join = (- db_session_with_containers.query(TenantAccountJoin)- .filter_by(tenant_id=tenant.id, account_id=account.id)- .first()- )- join.role = TenantAccountRole.NORMAL- db_session_with_containers.commit()-- # Setup mocks for feature service- mock_external_service_dependencies["feature_service"].get_features.return_value.can_replace_logo = True- mock_external_service_dependencies["tenant_service"].has_roles.return_value = False-- # Mock current_user for flask_login- with patch("services.workspace_service.current_user", account):- # Act: Execute the method under test- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- # Assert: Verify the expected outcomes- assert result is not None- assert result["id"] == tenant.id- assert result["name"] == tenant.name- assert result["plan"] == "professional"- assert result["status"] == tenant.status- assert result["role"] == TenantAccountRole.NORMAL- assert result["created_at"] == tenant.created_at- assert result["trial_end_reason"] is None-- # Verify custom config is not included for normal users- assert "custom_config" not in result-- # Verify database state- db_session_with_containers.refresh(tenant)- assert tenant.id is not None-- def test_get_tenant_info_with_admin_role_and_logo_replacement(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test tenant info retrieval for admin role with logo replacement enabled.-- This test verifies:- - Admin role can access custom config features- - Logo replacement functionality works for admin users- - Proper URL construction for logo replacement- - Custom config handling for admin role- """- # Arrange: Create test data- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )-- # Update the join to have admin role-- join = (- db_session_with_containers.query(TenantAccountJoin)- .filter_by(tenant_id=tenant.id, account_id=account.id)- .first()- )- join.role = TenantAccountRole.ADMIN- db_session_with_containers.commit()-- # Setup mocks for feature service and tenant service- mock_external_service_dependencies["feature_service"].get_features.return_value.can_replace_logo = True- mock_external_service_dependencies["tenant_service"].has_roles.return_value = True- mock_external_service_dependencies["dify_config"].FILES_URL = "https://cdn.example.com"-- # Mock current_user for flask_login- with patch("services.workspace_service.current_user", account):- # Act: Execute the method under test- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- # Assert: Verify the expected outcomes- assert result is not None- assert result["role"] == TenantAccountRole.ADMIN-- # Verify custom config is included for admin users- assert "custom_config" in result- assert result["custom_config"]["remove_webapp_brand"] is False- assert "replace_webapp_logo" in result["custom_config"]-- # Verify database state- db_session_with_containers.refresh(tenant)- assert tenant.id is not None-- def test_get_tenant_info_with_tenant_none(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test tenant info retrieval when tenant parameter is None.-- This test verifies:- - Proper handling of None tenant parameter- - Method returns None for invalid input- - No exceptions are raised for None input- - Graceful degradation for invalid data- """- # Arrange: No test data needed for this test-- # Act: Execute the method under test with None tenant- result = WorkspaceService.get_tenant_info(None, db_session_with_containers)-- # Assert: Verify the expected outcomes- assert result is None-- def test_get_tenant_info_with_custom_config_variations(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test tenant info retrieval with various custom config configurations.-- This test verifies:- - Different custom config combinations work correctly- - Logo replacement URL construction with various configs- - Brand removal functionality- - Edge cases in custom config handling- """- # Arrange: Create test data with different custom configs- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )-- # Test different custom config combinations- test_configs = [- # Case 1: Both logo and brand removal enabled- {"replace_webapp_logo": True, "remove_webapp_brand": True},- # Case 2: Only logo replacement enabled- {"replace_webapp_logo": True, "remove_webapp_brand": False},- # Case 3: Only brand removal enabled- {"replace_webapp_logo": False, "remove_webapp_brand": True},- # Case 4: Neither enabled- {"replace_webapp_logo": False, "remove_webapp_brand": False},- ]-- for config in test_configs:- # Update tenant custom config- tenant.custom_config = json.dumps(config)- db_session_with_containers.commit()-- # Setup mocks- mock_external_service_dependencies["feature_service"].get_features.return_value.can_replace_logo = True- mock_external_service_dependencies["tenant_service"].has_roles.return_value = True- mock_external_service_dependencies["dify_config"].FILES_URL = "https://files.example.com"-- # Mock current_user for flask_login- with patch("services.workspace_service.current_user", account):- # Act: Execute the method under test- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- # Assert: Verify the expected outcomes- assert result is not None- assert "custom_config" in result-- if config["replace_webapp_logo"]:- assert "replace_webapp_logo" in result["custom_config"]- if config["replace_webapp_logo"]:- expected_url = f"https://files.example.com/files/workspaces/{tenant.id}/webapp-logo"- assert result["custom_config"]["replace_webapp_logo"] == expected_url- else:- assert result["custom_config"]["replace_webapp_logo"] is None-- assert result["custom_config"]["remove_webapp_brand"] == config["remove_webapp_brand"]-- # Verify database state- db_session_with_containers.refresh(tenant)- assert tenant.id is not None-- def test_get_tenant_info_with_editor_role_and_limited_permissions(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test tenant info retrieval for editor role with limited permissions.-- This test verifies:- - Editor role has limited access to custom config features- - Proper role-based permission checking- - Custom config handling for different role levels- - Role hierarchy and permission boundaries- """- # Arrange: Create test data- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )-- # Update the join to have editor role-- join = (- db_session_with_containers.query(TenantAccountJoin)- .filter_by(tenant_id=tenant.id, account_id=account.id)- .first()- )- join.role = TenantAccountRole.EDITOR- db_session_with_containers.commit()-- # Setup mocks for feature service and tenant service- mock_external_service_dependencies["feature_service"].get_features.return_value.can_replace_logo = True- # Editor role should not have admin/owner permissions- mock_external_service_dependencies["tenant_service"].has_roles.return_value = False- mock_external_service_dependencies["dify_config"].FILES_URL = "https://cdn.example.com"-- # Mock current_user for flask_login- with patch("services.workspace_service.current_user", account):- # Act: Execute the method under test- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- # Assert: Verify the expected outcomes- assert result is not None- assert result["role"] == TenantAccountRole.EDITOR-- # Verify custom config is not included for editor users without admin privileges- assert "custom_config" not in result-- # Verify database state- db_session_with_containers.refresh(tenant)- assert tenant.id is not None-- def test_get_tenant_info_with_dataset_operator_role(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test tenant info retrieval for dataset operator role.-- This test verifies:- - Dataset operator role handling- - Role assignment for specialized roles- - Permission boundaries for dataset operators- - Custom config access for dataset operators- """- # Arrange: Create test data- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )-- # Update the join to have dataset operator role-- join = (- db_session_with_containers.query(TenantAccountJoin)- .filter_by(tenant_id=tenant.id, account_id=account.id)- .first()- )- join.role = TenantAccountRole.DATASET_OPERATOR- db_session_with_containers.commit()-- # Setup mocks for feature service and tenant service- mock_external_service_dependencies["feature_service"].get_features.return_value.can_replace_logo = True- # Dataset operator should not have admin/owner permissions- mock_external_service_dependencies["tenant_service"].has_roles.return_value = False- mock_external_service_dependencies["dify_config"].FILES_URL = "https://cdn.example.com"-- # Mock current_user for flask_login- with patch("services.workspace_service.current_user", account):- # Act: Execute the method under test- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- # Assert: Verify the expected outcomes- assert result is not None- assert result["role"] == TenantAccountRole.DATASET_OPERATOR-- # Verify custom config is not included for dataset operators without admin privileges- assert "custom_config" not in result-- # Verify database state- db_session_with_containers.refresh(tenant)- assert tenant.id is not None-- def test_get_tenant_info_with_complex_custom_config_scenarios(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test tenant info retrieval with complex custom config scenarios.-- This test verifies:- - Complex custom config combinations- - Edge cases in custom config handling- - URL construction with various configs- - Error handling for malformed configs- """- # Arrange: Create test data- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )-- # Test complex custom config scenarios- test_configs = [- # Case 1: Empty custom config- {},- # Case 2: Custom config with only logo replacement- {"replace_webapp_logo": True},- # Case 3: Custom config with only brand removal- {"remove_webapp_brand": True},- # Case 4: Custom config with additional fields- {- "replace_webapp_logo": True,- "remove_webapp_brand": False,- "custom_field": "custom_value",- "nested_config": {"key": "value"},- },- # Case 5: Custom config with null values- {"replace_webapp_logo": None, "remove_webapp_brand": None},- ]-- for config in test_configs:- # Update tenant custom config- tenant.custom_config = json.dumps(config)- db_session_with_containers.commit()-- # Setup mocks- mock_external_service_dependencies["feature_service"].get_features.return_value.can_replace_logo = True- mock_external_service_dependencies["tenant_service"].has_roles.return_value = True- mock_external_service_dependencies["dify_config"].FILES_URL = "https://files.example.com"-- # Mock current_user for flask_login- with patch("services.workspace_service.current_user", account):- # Act: Execute the method under test- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- # Assert: Verify the expected outcomes- assert result is not None- assert "custom_config" in result-- # Verify logo replacement handling- if config.get("replace_webapp_logo"):- assert "replace_webapp_logo" in result["custom_config"]- expected_url = f"https://files.example.com/files/workspaces/{tenant.id}/webapp-logo"- assert result["custom_config"]["replace_webapp_logo"] == expected_url- else:- assert result["custom_config"]["replace_webapp_logo"] is None-- # Verify brand removal handling- if "remove_webapp_brand" in config:- assert result["custom_config"]["remove_webapp_brand"] == config["remove_webapp_brand"]- else:- assert result["custom_config"]["remove_webapp_brand"] is False-- # Verify database state- db_session_with_containers.refresh(tenant)- assert tenant.id is not None-- def test_get_tenant_info_should_raise_assertion_when_join_missing(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """TenantAccountJoin must exist; missing join should raise AssertionError."""- fake = Faker()- account = Account(email=fake.email(), name=fake.name(), interface_language="en-US", status="active")- db_session_with_containers.add(account)- db_session_with_containers.commit()-- tenant = Tenant(name=fake.company(), status="normal", plan="basic")- db_session_with_containers.add(tenant)- db_session_with_containers.commit()-- # No TenantAccountJoin created- with patch("services.workspace_service.current_user", account):- with pytest.raises(AssertionError, match="TenantAccountJoin not found"):- WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- def test_get_tenant_info_should_set_replace_webapp_logo_to_none_when_flag_absent(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """replace_webapp_logo should be None when custom_config_dict does not have the key."""- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )- tenant.custom_config = json.dumps({})- db_session_with_containers.commit()-- mock_external_service_dependencies["feature_service"].get_features.return_value.can_replace_logo = True- mock_external_service_dependencies["tenant_service"].has_roles.return_value = True-- with patch("services.workspace_service.current_user", account):- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- assert result is not None- assert result["custom_config"]["replace_webapp_logo"] is None-- def test_get_tenant_info_should_use_files_url_for_logo_url(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """The logo URL should use dify_config.FILES_URL as the base."""- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )- tenant.custom_config = json.dumps({"replace_webapp_logo": True})- db_session_with_containers.commit()-- custom_base = "https://cdn.mycompany.io"- mock_external_service_dependencies["dify_config"].FILES_URL = custom_base- mock_external_service_dependencies["feature_service"].get_features.return_value.can_replace_logo = True- mock_external_service_dependencies["tenant_service"].has_roles.return_value = True-- with patch("services.workspace_service.current_user", account):- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- assert result is not None- assert result["custom_config"]["replace_webapp_logo"].startswith(custom_base)-- def test_get_tenant_info_should_not_include_cloud_fields_in_self_hosted(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """Cloud-only billing data should not appear in SELF_HOSTED mode."""- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )-- mock_external_service_dependencies["dify_config"].DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITY- feature = mock_external_service_dependencies["feature_service"].get_features.return_value- feature.can_replace_logo = False- mock_external_service_dependencies["tenant_service"].has_roles.return_value = False-- with patch("services.workspace_service.current_user", account):- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- assert result is not None- assert result["plan"] is None- assert "next_credit_reset_date" not in result- assert "trial_credits" not in result- assert "trial_credits_used" not in result-- def test_get_tenant_info_cloud_credit_reset_date(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """next_credit_reset_date should be present in CLOUD edition."""- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )-- mock_external_service_dependencies["dify_config"].DEPLOYMENT_EDITION = DeploymentEdition.CLOUD- feature = mock_external_service_dependencies["feature_service"].get_features.return_value- feature.can_replace_logo = False- feature.next_credit_reset_date = "2025-02-01"- feature.billing.subscription.plan = "professional"- mock_external_service_dependencies["tenant_service"].has_roles.return_value = False-- with (- patch("services.workspace_service.current_user", account),- patch("services.credit_pool_service.CreditPoolService.get_pool", return_value=None),- ):- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- assert result is not None- assert result["next_credit_reset_date"] == "2025-02-01"-- def test_get_tenant_info_cloud_paid_pool_not_full(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """trial_credits come from paid pool when plan is not sandbox and pool is not full."""- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )-- mock_external_service_dependencies["dify_config"].DEPLOYMENT_EDITION = DeploymentEdition.CLOUD- feature = mock_external_service_dependencies["feature_service"].get_features.return_value- feature.can_replace_logo = False- feature.next_credit_reset_date = "2025-02-01"- feature.billing.subscription.plan = "professional"- mock_external_service_dependencies["tenant_service"].has_roles.return_value = False-- paid_pool = MagicMock(quota_limit=1000, quota_used=200)-- with (- patch("services.workspace_service.current_user", account),- patch("services.credit_pool_service.CreditPoolService.get_pool", return_value=paid_pool),- ):- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- assert result is not None- assert result["trial_credits"] == 1000- assert result["trial_credits_used"] == 200-- def test_get_tenant_info_cloud_paid_pool_unlimited(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """quota_limit == -1 means unlimited; service should use paid pool."""- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )-- mock_external_service_dependencies["dify_config"].DEPLOYMENT_EDITION = DeploymentEdition.CLOUD- feature = mock_external_service_dependencies["feature_service"].get_features.return_value- feature.can_replace_logo = False- feature.next_credit_reset_date = "2025-02-01"- feature.billing.subscription.plan = "professional"- mock_external_service_dependencies["tenant_service"].has_roles.return_value = False-- paid_pool = MagicMock(quota_limit=-1, quota_used=999)-- with (- patch("services.workspace_service.current_user", account),- patch("services.credit_pool_service.CreditPoolService.get_pool", side_effect=[paid_pool, None]),- ):- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- assert result is not None- assert result["trial_credits"] == -1- assert result["trial_credits_used"] == 999-- def test_get_tenant_info_cloud_fall_back_to_trial_when_paid_full(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """When paid pool is exhausted, switch to trial pool."""- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )-- mock_external_service_dependencies["dify_config"].DEPLOYMENT_EDITION = DeploymentEdition.CLOUD- feature = mock_external_service_dependencies["feature_service"].get_features.return_value- feature.can_replace_logo = False- feature.next_credit_reset_date = "2025-02-01"- feature.billing.subscription.plan = "professional"- mock_external_service_dependencies["tenant_service"].has_roles.return_value = False-- paid_pool = MagicMock(quota_limit=500, quota_used=500)- trial_pool = CreditPoolBalance(- tenant_id=tenant.id,- pool_type="trial",- quota_limit=100,- quota_used=100,- exhausted_at=1748908800,- )-- with (- patch("services.workspace_service.current_user", account),- patch("services.credit_pool_service.CreditPoolService.get_pool", side_effect=[paid_pool, trial_pool]),- ):- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- assert result is not None- assert result["trial_credits"] == 100- assert result["trial_credits_used"] == 100- assert result["trial_credits_exhausted_at"] == 1748908800-- def test_get_tenant_info_cloud_fall_back_to_trial_when_paid_none(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """When paid_pool is None, fall back to trial pool."""- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )-- mock_external_service_dependencies["dify_config"].DEPLOYMENT_EDITION = DeploymentEdition.CLOUD- feature = mock_external_service_dependencies["feature_service"].get_features.return_value- feature.can_replace_logo = False- feature.next_credit_reset_date = "2025-02-01"- feature.billing.subscription.plan = "professional"- mock_external_service_dependencies["tenant_service"].has_roles.return_value = False-- trial_pool = MagicMock(quota_limit=50, quota_used=5)-- with (- patch("services.workspace_service.current_user", account),- patch("services.credit_pool_service.CreditPoolService.get_pool", side_effect=[None, trial_pool]),- ):- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- assert result is not None- assert result["trial_credits"] == 50- assert result["trial_credits_used"] == 5-- def test_get_tenant_info_cloud_sandbox_uses_trial_pool(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """When plan is SANDBOX, skip paid pool and use trial pool."""- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )-- mock_external_service_dependencies["dify_config"].DEPLOYMENT_EDITION = DeploymentEdition.CLOUD- feature = mock_external_service_dependencies["feature_service"].get_features.return_value- feature.can_replace_logo = False- feature.next_credit_reset_date = "2025-02-01"- feature.billing.subscription.plan = CloudPlan.SANDBOX- mock_external_service_dependencies["tenant_service"].has_roles.return_value = False-- paid_pool = MagicMock(quota_limit=1000, quota_used=0)- trial_pool = MagicMock(quota_limit=200, quota_used=20)-- with (- patch("services.workspace_service.current_user", account),- patch("services.credit_pool_service.CreditPoolService.get_pool", side_effect=[paid_pool, trial_pool]),- ):- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- assert result is not None- assert result["trial_credits"] == 200- assert result["trial_credits_used"] == 20-- def test_get_tenant_info_cloud_both_pools_none(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """When both paid and trial pools are absent, trial_credits should not be set."""- fake = Faker()- account, tenant = self._create_test_account_and_tenant(- db_session_with_containers, mock_external_service_dependencies- )-- mock_external_service_dependencies["dify_config"].DEPLOYMENT_EDITION = DeploymentEdition.CLOUD- feature = mock_external_service_dependencies["feature_service"].get_features.return_value- feature.can_replace_logo = False- feature.next_credit_reset_date = "2025-02-01"- feature.billing.subscription.plan = "professional"- mock_external_service_dependencies["tenant_service"].has_roles.return_value = False-- with (- patch("services.workspace_service.current_user", account),- patch("services.credit_pool_service.CreditPoolService.get_pool", side_effect=[None, None]),- ):- result = WorkspaceService.get_tenant_info(tenant, db_session_with_containers)-- assert result is not None- assert "trial_credits" not in result- assert "trial_credits_used" not in resultdiff --git a/api/tests/test_containers_integration_tests/services/tools/test_workflow_tools_manage_service.py b/api/tests/test_containers_integration_tests/services/tools/test_workflow_tools_manage_service.pyindex f05a0fb28da..80dc32ec3fa 100644--- a/api/tests/test_containers_integration_tests/services/tools/test_workflow_tools_manage_service.py+++ b/api/tests/test_containers_integration_tests/services/tools/test_workflow_tools_manage_service.py@@ -10,9 +10,9 @@ from core.tools.entities.tool_entities import WorkflowToolParameterConfigurationfrom core.tools.errors import WorkflowToolHumanInputNotSupportedErrorfrom models.tools import WorkflowToolProviderfrom models.workflow import Workflow as WorkflowModel-from services.account_service import AccountService, TenantServicefrom services.app_service import AppService, CreateAppParamsfrom services.tools.workflow_tools_manage_service import WorkflowToolManageService+from tests.test_containers_integration_tests.helpers import accounts as account_fixturesfrom tests.test_containers_integration_tests.helpers import generate_valid_password@@ -26,7 +26,7 @@ class TestWorkflowToolManageService:patch("services.app_service.SystemFeatureService") as mock_feature_service,patch("services.app_service.EnterpriseService") as mock_enterprise_service,patch("services.app_service.ModelManager.for_tenant") as mock_model_manager,- patch("services.account_service.SystemFeatureService") as mock_account_feature_service,+ patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service,patch("services.tools.workflow_tools_manage_service.WorkflowToolProviderController") as mock_workflow_tool_provider_controller,@@ -82,14 +82,14 @@ class TestWorkflowToolManageService:mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenant- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create app with realistic datadiff --git a/api/tests/test_containers_integration_tests/services/workspace/test_invitations.py b/api/tests/test_containers_integration_tests/services/workspace/test_invitations.pynew file mode 100644index 00000000000..3d3678b2059--- /dev/null+++ b/api/tests/test_containers_integration_tests/services/workspace/test_invitations.py@@ -0,0 +1,162 @@+"""Invitation issuance and activation through real PostgreSQL and Redis adapters."""++import json+from hashlib import sha256+from unittest.mock import Mock+from uuid import uuid4++import pytest+from sqlalchemy import select+from sqlalchemy.orm import Session++from configs import dify_config+from enums import DeploymentEdition+from extensions.ext_application_services import application_services+from extensions.ext_redis import redis_client+from machinery.context import RequestContext+from models.account import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccountRole, TenantStatus+from services.account.adapters import RedisInvitationTokenStore+from services.account_errors import InvalidInvitationError+from services.entities.account_activation_entities import ActivationCommand, InvitationLookup, InvitationToken+from services.workspace import gateways+++def workspace(db_session_with_containers: Session, monkeypatch: pytest.MonkeyPatch) -> tuple[Tenant, Account, Account]:+ monkeypatch.setattr(dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)+ monkeypatch.setattr(dify_config, "RBAC_ENABLED", False)+ tenant = Tenant(name="Inviting workspace", status=TenantStatus.NORMAL)+ owner = Account(name="Owner", email=f"owner-{uuid4()}@example.com", status=AccountStatus.ACTIVE)+ invited = Account(name="Invited", email=f"invited-{uuid4()}@example.com", status=AccountStatus.PENDING)+ db_session_with_containers.add_all(+ [+ tenant,+ owner,+ invited,+ TenantAccountJoin(tenant_id=tenant.id, account_id=owner.id, role=TenantAccountRole.OWNER, current=True),+ ]+ )+ db_session_with_containers.commit()+ return tenant, owner, invited++[email protected]("status", [AccountStatus.PENDING, AccountStatus.ACTIVE])+def test_invitation_token_round_trip_and_acceptance(+ workspace: tuple[Tenant, Account, Account],+ db_session_with_containers: Session,+ monkeypatch: pytest.MonkeyPatch,+ status: AccountStatus,+) -> None:+ tenant, owner, invited = workspace+ invited.status = status+ db_session_with_containers.commit()+ send = Mock(spec=gateways.send_invite_member_mail_task.delay)+ monkeypatch.setattr(gateways.send_invite_member_mail_task, "delay", send)+ services = application_services()++ invitation = services.workspaces.invitations.invite(+ RequestContext("request", None, owner.id, tenant.id), invited.email, "en-US", "admin"+ )+ token = invitation.token+ assert invitation.account_id == invited.id++ token_key = f"member_invite:token:{token}"+ payload = redis_client.get(token_key)+ assert payload is not None+ assert json.loads(payload) == {+ "account_id": invited.id,+ "email": invited.email,+ "workspace_id": tenant.id,+ "role": "admin",+ "requires_setup": status == AccountStatus.PENDING,+ }+ assert 0 < redis_client.ttl(token_key) <= dify_config.INVITE_EXPIRY_HOURS * 3600+ send.assert_called_once_with(+ language="en-US", to=invited.email, token=token, inviter_name=owner.name, workspace_name=tenant.name+ )+ assert services.workspaces.members.get_role(tenant.id, invited.id) == (+ TenantAccountRole.ADMIN if status == AccountStatus.PENDING else None+ )+ lookup = InvitationLookup(workspace_id=None, email=None, token=token)+ checked = services.accounts.activation.check(lookup)+ assert checked.is_valid+ assert checked.data is not None+ assert checked.data.email == invited.email+ assert checked.data.workspace_id == tenant.id+ assert checked.data.workspace_name == tenant.name+ assert checked.data.account_status == status+ assert checked.data.requires_setup is (status == AccountStatus.PENDING)++ services.accounts.activation.activate(+ ActivationCommand(invitation=lookup, name="Accepted", interface_language="en-US", timezone="UTC"),+ authenticated_account_id=invited.id,+ )++ db_session_with_containers.expire_all()+ assert invited.status == AccountStatus.ACTIVE+ assert services.workspaces.members.get_role(tenant.id, invited.id) == TenantAccountRole.ADMIN+ membership = db_session_with_containers.scalar(+ select(TenantAccountJoin).where(+ TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == invited.id+ )+ )+ assert membership is not None+ assert membership.current+ assert redis_client.get(token_key) is None+ assert not services.accounts.activation.check(lookup).is_valid+ with pytest.raises(InvalidInvitationError):+ services.accounts.activation.activate(ActivationCommand(invitation=lookup), authenticated_account_id=invited.id)++[email protected]("mixed_case", [False, True])+def test_previous_workspace_scoped_token_format_can_be_accepted_and_revoked(+ workspace: tuple[Tenant, Account, Account], mixed_case: bool+) -> None:+ tenant, _, invited = workspace+ token = str(uuid4())+ email_hash = sha256(invited.email.encode()).hexdigest()+ key = f"member_invite_token:{tenant.id}, {email_hash}:{token}"+ redis_client.setex(key, 3600, invited.id)+ lookup = InvitationLookup(+ workspace_id=tenant.id, email=invited.email.upper() if mixed_case else invited.email, token=token+ )+ services = application_services()++ checked = services.accounts.activation.check(lookup)+ assert checked.is_valid+ assert checked.data is not None+ assert checked.data.requires_setup+ assert checked.data.email == invited.email+ services.accounts.activation.activate(+ ActivationCommand(invitation=lookup, name="Accepted", interface_language="en-US", timezone="UTC"),+ authenticated_account_id=None,+ )++ assert redis_client.get(key) is None+ assert not services.accounts.activation.check(lookup).is_valid+ assert services.workspaces.members.get_role(tenant.id, invited.id) == TenantAccountRole.NORMAL++[email protected]("reason", ["expired", "missing-account", "missing-workspace", "archived", "wrong-email"])+def test_invalid_invitation_state_is_rejected(+ workspace: tuple[Tenant, Account, Account], db_session_with_containers: Session, reason: str+) -> None:+ tenant, _, invited = workspace+ if reason == "archived":+ tenant.status = TenantStatus.ARCHIVE+ db_session_with_containers.commit()+ token = RedisInvitationTokenStore(redis=redis_client).create(+ InvitationToken(+ account_id=str(uuid4()) if reason == "missing-account" else invited.id,+ email="[email protected]" if reason == "wrong-email" else invited.email,+ workspace_id=str(uuid4()) if reason == "missing-workspace" else tenant.id,+ )+ )+ if reason == "expired":+ redis_client.pexpire(f"member_invite:token:{token}", 0)+ lookup = InvitationLookup(workspace_id=None, email=None, token=token)+ activation = application_services().accounts.activation++ assert not activation.check(lookup).is_valid+ with pytest.raises(InvalidInvitationError):+ activation.activate(ActivationCommand(invitation=lookup), authenticated_account_id=invited.id)diff --git a/api/tests/test_containers_integration_tests/tasks/test_clean_notion_document_task.py b/api/tests/test_containers_integration_tests/tasks/test_clean_notion_document_task.pyindex d9cdd9aef79..781122c01e1 100644--- a/api/tests/test_containers_integration_tests/tasks/test_clean_notion_document_task.py+++ b/api/tests/test_containers_integration_tests/tasks/test_clean_notion_document_task.py@@ -17,8 +17,8 @@ from sqlalchemy.orm import Sessionfrom core.rag.index_processor.constant.index_type import IndexStructureTypefrom models.dataset import Dataset, Document, DocumentSegmentfrom models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatus, SegmentStatus-from services.account_service import AccountService, TenantServicefrom tasks.clean_notion_document_task import clean_notion_document_task+from tests.test_containers_integration_tests.helpers import accounts as account_fixturesfrom tests.test_containers_integration_tests.helpers import generate_valid_password@@ -37,7 +37,7 @@ class TestCleanNotionDocumentTask:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.account_service.SystemFeatureService") as mock_account_feature_service,+ patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service,):# Setup default mock returns for account servicemock_account_feature_service.is_registration_allowed.return_value = True@@ -67,14 +67,14 @@ class TestCleanNotionDocumentTask:fake = Faker()# Create test data- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create dataset@@ -189,14 +189,14 @@ class TestCleanNotionDocumentTask:fake = Faker()# Create test data- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create dataset@@ -229,14 +229,14 @@ class TestCleanNotionDocumentTask:fake = Faker()# Create test data- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Test different index types@@ -316,14 +316,14 @@ class TestCleanNotionDocumentTask:fake = Faker()# Create test data- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create dataset@@ -399,14 +399,14 @@ class TestCleanNotionDocumentTask:fake = Faker()# Create test data- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create dataset@@ -502,14 +502,14 @@ class TestCleanNotionDocumentTask:fake = Faker()# Create test data- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create dataset@@ -604,14 +604,14 @@ class TestCleanNotionDocumentTask:fake = Faker()# Create test data- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create dataset@@ -697,14 +697,14 @@ class TestCleanNotionDocumentTask:fake = Faker()# Create test data- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create dataset@@ -802,16 +802,14 @@ class TestCleanNotionDocumentTask:datasets = []for i in range(3):- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(- account, name=fake.company(), session=db_session_with_containers- )+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantaccounts.append(account)tenants.append(tenant)@@ -914,14 +912,14 @@ class TestCleanNotionDocumentTask:fake = Faker()# Create test data- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create dataset@@ -1021,14 +1019,14 @@ class TestCleanNotionDocumentTask:fake = Faker()# Create test data- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenant# Create dataset with built-in fields enableddiff --git a/api/tests/test_containers_integration_tests/tasks/test_deal_dataset_vector_index_task.py b/api/tests/test_containers_integration_tests/tasks/test_deal_dataset_vector_index_task.pyindex 6499d251048..91131d9970f 100644--- a/api/tests/test_containers_integration_tests/tasks/test_deal_dataset_vector_index_task.py+++ b/api/tests/test_containers_integration_tests/tasks/test_deal_dataset_vector_index_task.py@@ -17,8 +17,8 @@ from sqlalchemy.orm import Sessionfrom core.rag.index_processor.constant.index_type import IndexStructureTypefrom models.dataset import Dataset, Document, DocumentSegmentfrom models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatus, SegmentStatus-from services.account_service import AccountService, TenantServicefrom tasks.deal_dataset_vector_index_task import deal_dataset_vector_index_task+from tests.test_containers_integration_tests.helpers import accounts as account_fixturesfrom tests.test_containers_integration_tests.helpers import generate_valid_password@@ -29,7 +29,7 @@ class TestDealDatasetVectorIndexTask:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.account_service.SystemFeatureService") as mock_account_feature_service,+ patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service,):# Setup default mock returns for account servicemock_account_feature_service.is_registration_allowed.return_value = True@@ -62,14 +62,14 @@ class TestDealDatasetVectorIndexTask:Returns a tuple of (account, tenant) where tenant is guaranteed to be non-None."""fake = Faker()- account = AccountService.create_account(+ account = account_fixtures.create_account(email=fake.email(),name=fake.name(),interface_language="en-US",password=generate_valid_password(fake),session=db_session_with_containers,)- TenantService.create_owner_tenant_if_not_exist(account, name=fake.company(), session=db_session_with_containers)+ account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)tenant = account.current_tenantassert tenant is not Nonereturn account, tenantdiff --git a/api/tests/unit_tests/.ruff.toml b/api/tests/unit_tests/.ruff.tomlindex b7fcaba4b7a..3fd4cc35648 100644--- a/api/tests/unit_tests/.ruff.toml+++ b/api/tests/unit_tests/.ruff.toml@@ -53,7 +53,6 @@ extend-select = ["ANN401", "ARG"]"controllers/console/test_human_input_form.py" = ["ARG001", "ARG005"]"controllers/console/test_init_validate.py" = ["ARG005"]"controllers/console/test_workspace_account.py" = ["ARG002"]-"controllers/console/test_workspace_members.py" = ["ARG002", "ARG005"]"controllers/console/test_wraps.py" = ["ARG001", "ARG002"]"controllers/console/workspace/test_load_balancing_config.py" = ["ARG001"]"controllers/console/workspace/test_plugin.py" = ["ARG002", "TID251"]diff --git a/api/tests/unit_tests/account_domain.py b/api/tests/unit_tests/account_domain.pynew file mode 100644index 00000000000..23553ed450e--- /dev/null+++ b/api/tests/unit_tests/account_domain.py@@ -0,0 +1,91 @@+"""Account test composition with real persistence and explicit external ports."""++from dataclasses import dataclass+from datetime import datetime+from unittest.mock import Mock++from sqlalchemy.orm import Session, sessionmaker++from repositories.account.repository import SQLAlchemyAccountRepository+from repositories.workspace.workspace_repository import WorkspaceRepository+from services.account.login_service import AccountSessionGateway, ConsoleAuthSecurityGateway+from services.account.service import AccountLifecyclePolicy, AccountService+from services.account_password_hasher import DefaultAccountPasswordHasher+from services.workspace.gateways import WorkspaceProvisioningEffectsGateway+from services.workspace.member_service import (+ WorkspaceInvitationDelivery,+ WorkspaceInvitationService,+ WorkspaceMemberAccessGateway,+ WorkspaceMemberService,+)+from services.workspace.provisioning_service import WorkspaceProvisioningService+++@dataclass+class AccountDomain:+ accounts: AccountService+ members: WorkspaceMemberService+ provisioning: WorkspaceProvisioningService+ invitations: WorkspaceInvitationService+ repository: SQLAlchemyAccountRepository+ workspaces: WorkspaceRepository+ policy: Mock+ access: Mock+ delivery: Mock+ sessions: Mock+ security: Mock+++def build_account_domain(session_factory: sessionmaker[Session]) -> AccountDomain:+ repository = SQLAlchemyAccountRepository(session_factory)+ workspaces = WorkspaceRepository(session_factory)+ policy = Mock(spec=AccountLifecyclePolicy)+ policy.is_registration_allowed.return_value = True+ policy.has_account_capacity.return_value = True+ policy.is_workspace_creation_allowed.return_value = True+ policy.has_workspace_capacity.return_value = True+ policy.get_email_freeze_type.return_value = None+ policy.validate_timezone.side_effect = lambda timezone: timezone+ access = Mock(spec=WorkspaceMemberAccessGateway)+ access.rbac_enabled = False+ access.permission_keys.return_value = {"workspace.member.manage", "workspace.role.manage"}+ access.is_owner.return_value = False+ members = WorkspaceMemberService(workspaces=workspaces, accounts=repository, access=access)+ provisioning = WorkspaceProvisioningService(+ owners=repository,+ provisioning=workspaces,+ effects=WorkspaceProvisioningEffectsGateway(session_factory=session_factory),+ policies=policy,+ memberships=workspaces,+ members=members,+ )+ sessions = Mock(spec=AccountSessionGateway)+ security = Mock(spec=ConsoleAuthSecurityGateway)+ accounts = AccountService(+ accounts=repository,+ policies=policy,+ passwords=DefaultAccountPasswordHasher(),+ workspaces=provisioning,+ sessions=sessions,+ security=security,+ now=lambda: datetime(2026, 1, 1),+ )+ delivery = Mock(spec=WorkspaceInvitationDelivery)+ delivery.requires_capacity_check = False+ delivery.create.return_value = "invitation-token"+ invitations = WorkspaceInvitationService(+ accounts=accounts, workspaces=workspaces, members=members, invitations=delivery+ )+ return AccountDomain(+ accounts,+ members,+ provisioning,+ invitations,+ repository,+ workspaces,+ policy,+ access,+ delivery,+ sessions,+ security,+ )diff --git a/api/tests/unit_tests/commands/test_account_commands.py b/api/tests/unit_tests/commands/test_account_commands.pyindex bbcc5d3e704..cdfb7bd9567 100644--- a/api/tests/unit_tests/commands/test_account_commands.py+++ b/api/tests/unit_tests/commands/test_account_commands.py@@ -8,7 +8,7 @@ from commands.account import reset_email, reset_passworddef test_reset_password_does_not_swallow_keyboard_interrupt(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(- "commands.account.AccountService.get_account_by_email_with_case_fallback",+ "commands.account.application_services",Mock(return_value=Mock()),)monkeypatch.setattr("commands.account.valid_password", Mock(side_effect=KeyboardInterrupt))@@ -24,7 +24,7 @@ def test_reset_password_does_not_swallow_keyboard_interrupt(monkeypatch: pytest.def test_reset_email_does_not_swallow_keyboard_interrupt(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(- "commands.account.AccountService.get_account_by_email_with_case_fallback",+ "commands.account.application_services",Mock(return_value=Mock()),)monkeypatch.setattr("commands.account.email_validate", Mock(side_effect=KeyboardInterrupt))diff --git a/api/tests/unit_tests/conftest.py b/api/tests/unit_tests/conftest.pyindex db8ba7e1809..5afbd4ddb3d 100644--- a/api/tests/unit_tests/conftest.py+++ b/api/tests/unit_tests/conftest.py@@ -14,6 +14,10 @@ from sqlalchemy import create_enginefrom sqlalchemy.engine import URL, Enginefrom sqlalchemy.orm import Session, sessionmaker+if TYPE_CHECKING:+ from extensions.ext_application_services import ApplicationServices+ from tests.unit_tests.account_domain import AccountDomain+# Getting the absolute path of the current file's directoryABS_PATH = os.path.dirname(os.path.abspath(__file__))@@ -253,6 +257,53 @@ def persist_service_api_dataset_owner(session.commit()+def account_domain(+ sqlite_session_factory: sessionmaker[Session],+ monkeypatch: pytest.MonkeyPatch,+ config_overrides: Callable[..., None],+) -> AccountDomain:+ from blinker import Signal++ from enums import DeploymentEdition+ from services.workspace import gateways+ from tests.unit_tests.account_domain import build_account_domain++ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY, RBAC_ENABLED=False)+ monkeypatch.setattr(gateways, "generate_key_pair", lambda _workspace_id: "public-key")+ monkeypatch.setattr(gateways, "tenant_was_created", Signal())+ return build_account_domain(sqlite_session_factory)+++def account_application_services(+ sqlite_session_factory: sessionmaker[Session], account_domain: AccountDomain+) -> ApplicationServices:+ from dataclasses import replace+ from unittest.mock import Mock++ from enums import DeploymentEdition+ from extensions.ext_application_services import build_application_services+ from extensions.ext_redis import RedisClientWrapper++ services = build_application_services(+ database_client=sqlite_session_factory,+ deployment_edition=DeploymentEdition.COMMUNITY,+ initialization_password="",+ redis=Mock(spec=RedisClientWrapper),+ )+ return replace(+ services,+ accounts=replace(services.accounts, lifecycle=account_domain.accounts),+ workspaces=replace(+ services.workspaces,+ members=account_domain.members,+ provisioning=account_domain.provisioning,+ invitations=account_domain.invitations,+ ),+ )++@pytest.fixturedef app_services(sqlite_session_factory: sessionmaker[Session]) -> AppServices:from unittest.mock import Mockdiff --git a/api/tests/unit_tests/controllers/common/test_errors.py b/api/tests/unit_tests/controllers/common/test_errors.pyindex ada7e6d379e..417882ceef0 100644--- a/api/tests/unit_tests/controllers/common/test_errors.py+++ b/api/tests/unit_tests/controllers/common/test_errors.py@@ -1,4 +1,8 @@import pytest+from flask import Flask+from flask.typing import ResponseReturnValue+from flask_restx import Api, Resource+from werkzeug.exceptions import Forbiddenfrom controllers.common.errors import (BlockedFileExtensionError,@@ -15,7 +19,55 @@ from controllers.common.errors import (TooManyFilesError,UnsupportedFileTypeError,)+from controllers.console import api as console_api+from controllers.service_api import api as service_apifrom libs.exception import BaseHTTPException+from libs.external_api import ExternalApi+from services.errors.base import NoPermissionError+from services.errors.workspace import WorkspaceApplicationError++[email protected]("source_api", [console_api, service_api], ids=["console", "service_api"])+ ("error", "status", "code", "message"),+ [+ (NoPermissionError("Access denied"), 400, "invalid_param", "Access denied"),+ (ValueError("Invalid input"), 400, "invalid_param", "Invalid input"),+ (Forbidden("Access denied"), 403, "forbidden", "Access denied"),+ (WorkspaceApplicationError("unmapped workspace failure"), 500, "unknown", "Internal Server Error"),+ (RuntimeError("backend detail"), 500, "unknown", "Internal Server Error"),+ ],+)+def test_surface_permission_error_mapping_preserves_other_responses(+ source_api: Api, error: Exception, status: int, code: str, message: str+) -> None:+ app = Flask(__name__)+ api = Api(app, doc=False)+ # Use production registration and ordering; do not mutate the shared API instance.+ api.error_handlers = source_api.error_handlers.copy()++ class Endpoint(Resource):+ def get(self) -> ResponseReturnValue:+ raise error++ api.add_resource(Endpoint, "/error")+ response = app.test_client().get("/error")+ assert response.status_code == status+ assert response.json == {"code": code, "message": message, "status": status}+++def test_permission_error_mapping_is_not_registered_on_generic_apis() -> None:+ app = Flask(__name__)+ api = ExternalApi(app)++ class Endpoint(Resource):+ def get(self) -> ResponseReturnValue:+ raise NoPermissionError("internal permission detail")++ api.add_resource(Endpoint, "/error")+ response = app.test_client().get("/error")+ assert response.status_code == 500+ assert response.json == {"code": "unknown", "message": "Internal Server Error", "status": 500}class TestFilenameNotExistsError:diff --git a/api/tests/unit_tests/controllers/console/app/test_app_import_api.py b/api/tests/unit_tests/controllers/console/app/test_app_import_api.pyindex 074d0adb78a..0ce78d204ad 100644--- a/api/tests/unit_tests/controllers/console/app/test_app_import_api.py+++ b/api/tests/unit_tests/controllers/console/app/test_app_import_api.py@@ -20,7 +20,7 @@ from services.app.console_gateway import EnterpriseConsoleAppAccessfrom services.app_dsl_service import AppDslService, PendingDatafrom services.enterprise.enterprise_service import EnterpriseServicefrom services.entities.dsl_entities import Import, ImportStatus-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.plugin.dependencies_analysis import DependenciesAnalysisServicefrom services.system_feature_service import SystemFeatureServicediff --git a/api/tests/unit_tests/controllers/console/app/test_console_app_api.py b/api/tests/unit_tests/controllers/console/app/test_console_app_api.pyindex f244d27d4da..5b6d2adf702 100644--- a/api/tests/unit_tests/controllers/console/app/test_console_app_api.py+++ b/api/tests/unit_tests/controllers/console/app/test_console_app_api.py@@ -335,11 +335,11 @@ def test_create_quota_is_part_of_admission_and_precedes_application_call("controllers.console.wraps.FeatureService.get_features",lambda *_args, **_kwargs: FeatureModel(apps=LimitationModel(size=1, limit=1)),)- injector = inspect.unwrap(- controller.AppListApi.post, stop=lambda f: "allowed_roles" in inspect.getclosurevars(f).nonlocals+ admission = inspect.unwrap(+ controller.AppListApi.post, stop=lambda f: inspect.getclosurevars(f).nonlocals.get("resource") == "apps")with app.test_request_context(method="POST", json={"name": "Example", "mode": "chat"}), pytest.raises(Forbidden):- injector(controller.AppListApi())+ admission(controller.AppListApi())assert boundary.calls == []diff --git a/api/tests/unit_tests/controllers/console/auth/test_account_activation.py b/api/tests/unit_tests/controllers/console/auth/test_account_activation.pyindex e909ebbea2e..b7c3081bb4e 100644--- a/api/tests/unit_tests/controllers/console/auth/test_account_activation.py+++ b/api/tests/unit_tests/controllers/console/auth/test_account_activation.py@@ -1,6 +1,5 @@"""Transport-boundary tests for account invitation activation."""-from types import SimpleNamespacefrom unittest.mock import Mock, patchimport pytest@@ -16,15 +15,11 @@ from controllers.console.error import (from controllers.console.error import (EmailDomainSuspendedError as EmailDomainSuspendedHTTPError,)-from services.account_activation_service import (- AccountActivationService,- FrozenAccountError,- InvalidInvitationError,- InvitationAccountMismatchError,-)-from services.account_activation_service import (- EmailDomainSuspendedError as EmailDomainSuspendedRegistrationError,-)+from libs.login import AccountWithTenant+from models.account import Account+from services.account_activation_service import AccountActivationService+from services.account_errors import AccountEmailDomainSuspendedError as EmailDomainSuspendedRegistrationError+from services.account_errors import FrozenAccountError, InvalidInvitationError, InvitationAccountMismatchErrorfrom services.entities.account_activation_entities import (ActivationCheckData,ActivationCheckResult,@@ -45,8 +40,14 @@ def activation_service() -> Mock:return Mock(spec=AccountActivationService)-def _services(service: Mock) -> SimpleNamespace:- return SimpleNamespace(account_activation=service)+def _services(service: Mock) -> Mock:+ from extensions.application_services.account import AccountServices+ from extensions.ext_application_services import ApplicationServices++ services = Mock(spec=ApplicationServices)+ services.accounts = Mock(spec=AccountServices)+ services.accounts.activation = service+ return servicesclass TestActivateCheckApi:@@ -137,6 +138,8 @@ class TestActivateApi:"interface_language": "en-US","timezone": "UTC",}+ account = Account(name="User", email="[email protected]")+ account.id = "account-123"with (app.test_request_context("/activate", method="POST", json=payload),patch(@@ -146,7 +149,10 @@ class TestActivateApi:patch("controllers.console.auth.activate.extract_access_token", return_value="access-token"),patch("controllers.console.auth.activate.current_account_with_tenant",- return_value=SimpleNamespace(account=SimpleNamespace(id="account-123")),+ return_value=AccountWithTenant(+ account=account,+ tenant_id="workspace-123",+ ),),):response = ActivateApi().post()diff --git a/api/tests/unit_tests/controllers/console/auth/test_email_register.py b/api/tests/unit_tests/controllers/console/auth/test_email_register.pyindex 2189682f78a..6bd87d28615 100644--- a/api/tests/unit_tests/controllers/console/auth/test_email_register.py+++ b/api/tests/unit_tests/controllers/console/auth/test_email_register.py@@ -35,7 +35,7 @@ from controllers.console.error import (SeatsLimitExceeded,)from enums import DeploymentEdition-from services.account_email_registration_service import AccountEmailRegistrationService+from services.account.email_registration_service import AccountEmailRegistrationServicefrom services.account_errors import (AccountEmailAlreadyInUseError,AccountEmailDomainSuspendedError,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 7425178fd3f..faecf62c472 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@@ -38,8 +38,8 @@ from controllers.console.error import ()from enums import DeploymentEditionfrom services import account_errors+from services.entities.account_entities import AccountSessionTokensfrom services.entities.account_login_entities import (- AuthTokenPair,EmailCodeLoginCommand,EmailCodeSendCommand,PasswordLoginCommand,@@ -47,7 +47,7 @@ from services.entities.account_login_entities import ()TEST_TOKEN = "00000000-0000-4000-8000-000000000001"-TOKEN_PAIR = AuthTokenPair(access_token="access-token", refresh_token="refresh-token", csrf_token="csrf-token")+TOKENS = AccountSessionTokens(access_token="access-token", refresh_token="refresh-token", csrf_token="csrf-token")@dataclass@@ -69,7 +69,7 @@ class FakeAuthenticationService:self.password_commands.append(command)self._raise_if_needed()return PasswordLoginResult(- token_pair=TOKEN_PAIR if self.workspace_found else None,+ tokens=TOKENS if self.workspace_found else None,workspace_found=self.workspace_found,)@@ -86,15 +86,15 @@ class FakeAuthenticationService:self._raise_if_needed()return "email-code-token"- def login_with_email_code(self, command: EmailCodeLoginCommand) -> AuthTokenPair:+ def login_with_email_code(self, command: EmailCodeLoginCommand) -> AccountSessionTokens:self.email_code_login_commands.append(command)self._raise_if_needed()- return TOKEN_PAIR+ return TOKENS- def refresh(self, refresh_token: str) -> AuthTokenPair:+ def refresh(self, refresh_token: str) -> AccountSessionTokens:self.refresh_tokens.append(refresh_token)self._raise_if_needed()- return TOKEN_PAIR+ return TOKENS@pytest.fixture(autouse=True)diff --git a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline.py b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline.pyindex 36032f3650c..6e00620aebd 100644--- a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline.py+++ b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline.py@@ -25,7 +25,7 @@ from models.account import Account, TenantAccountRolefrom models.dataset import Pipeline, PipelineCustomizedTemplatefrom models.engine import dbfrom services.entities.knowledge_entities.rag_pipeline_entities import PipelineTemplateInfoEntity-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.errors.rag_pipeline import RagPipelineResourceNotFoundErrorfrom tests.unit_tests.config_override import config_overrides_contextfrom tests.unit_tests.controllers.rbac_introspection import rbac_checksdiff --git a/api/tests/unit_tests/controllers/console/datasets/test_hit_testing_base.py b/api/tests/unit_tests/controllers/console/datasets/test_hit_testing_base.pyindex bc7d18b8fc0..8054d21b633 100644--- a/api/tests/unit_tests/controllers/console/datasets/test_hit_testing_base.py+++ b/api/tests/unit_tests/controllers/console/datasets/test_hit_testing_base.py@@ -3,7 +3,7 @@ from unittest.mock import Mock, patchimport pytestfrom werkzeug.exceptions import Forbidden, InternalServerError, NotFound-import services+import services.errors.basefrom controllers.console.app.error import (CompletionRequestError,ProviderModelCurrentlyNotSupportError,@@ -117,7 +117,7 @@ class TestGetAndValidateDataset:patch.object(DatasetService,"check_dataset_permission",- side_effect=services.errors.account.NoPermissionError("no access"),+ side_effect=services.errors.base.NoPermissionError("no access"),),):with pytest.raises(Forbidden, match="no access"):diff --git a/api/tests/unit_tests/controllers/console/datasets/test_metadata.py b/api/tests/unit_tests/controllers/console/datasets/test_metadata.pyindex 63c28b60a33..55200cc8805 100644--- a/api/tests/unit_tests/controllers/console/datasets/test_metadata.py+++ b/api/tests/unit_tests/controllers/console/datasets/test_metadata.py@@ -1,19 +1,22 @@"""Console metadata routes use admission, explicit context, and response models."""from types import SimpleNamespace-from unittest.mock import create_autospec+from unittest.mock import Mock, create_autospecfrom uuid import uuid4import pytestfrom flask import Flask+from flask.testing import FlaskClientfrom flask_restx import Apifrom controllers.common.rbac import DatasetId, RBACPermission+from controllers.console import api as console_apifrom controllers.console import console_nsfrom controllers.console.datasets.metadata import DatasetMetadataCreateApifrom enums import DeploymentEditionfrom libs.login import AccountWithTenantfrom models.account import Account, TenantAccountRole+from services.errors.base import NoPermissionErrorfrom services.errors.metadata import MetadataResourceNotFoundErrorfrom services.knowledge.dataset_access import DatasetAccessDeniedError, DatasetNotFoundErrorfrom services.knowledge.metadata.application import MetadataService@@ -26,7 +29,9 @@ def routes(monkeypatch: pytest.MonkeyPatch, config_overrides):config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD, LOGIN_DISABLED=True, RBAC_ENABLED=False)app = Flask(__name__)app.config.update(TESTING=False, PROPAGATE_EXCEPTIONS=False)- Api(app).add_namespace(console_ns, path="/console/api")+ api = Api(app)+ api.error_handlers = console_api.error_handlers.copy()+ api.add_namespace(console_ns, path="/console/api")account = Account(name="Owner", email="[email protected]")account.id = "account-1"account.role = TenantAccountRole.OWNER@@ -41,6 +46,24 @@ def routes(monkeypatch: pytest.MonkeyPatch, config_overrides):return app.test_client(), service+ ("error", "status", "code", "message"),+ [+ (NoPermissionError("Access denied"), 400, "invalid_param", "Access denied"),+ (RuntimeError("backend detail"), 500, "unknown", "Internal Server Error"),+ ],+)+def test_metadata_permission_error_http_contract(+ routes: tuple[FlaskClient, Mock], error: Exception, status: int, code: str, message: str+) -> None:+ client, service = routes+ service.require_dataset.side_effect = error+ response = client.post(f"/console/api/datasets/{uuid4()}/metadata", json={"type": "string", "name": "author"})+ assert response.status_code == status+ assert response.json == {"code": code, "message": message, "status": status}+ service.create_metadata.assert_not_called()++def test_create_serializes_result_and_passes_actor(routes):client, service = routesdataset_id = str(uuid4())diff --git a/api/tests/unit_tests/controllers/console/explore/test_installed_app.py b/api/tests/unit_tests/controllers/console/explore/test_installed_app.pyindex b0c2ddeef1b..a43d7e6f787 100644--- a/api/tests/unit_tests/controllers/console/explore/test_installed_app.py+++ b/api/tests/unit_tests/controllers/console/explore/test_installed_app.py@@ -19,7 +19,7 @@ from models.account import TenantAccountRolefrom models.model import AppMode, AppModelConfig, IconTypefrom models.workflow import Workflow, WorkflowKind, WorkflowTypefrom repositories.installed_app_repository import SQLAlchemyInstalledAppRepository-from repositories.workspace_query_repository import WorkspaceQueryRepository+from repositories.workspace.workspace_repository import WorkspaceRepositoryfrom services.installed_app_access_service import InstalledAppAccessServicefrom services.installed_app_service import InstalledAppServicefrom services.webapp_access_query_service import WebAppAccessUnavailableError@@ -118,7 +118,7 @@ def management(installed_apps=_InstalledAppServices(management=InstalledAppService(installed_apps=SQLAlchemyInstalledAppRepository(session_factory=factory),- get_workspace_role=WorkspaceQueryRepository(factory).get_account_role,+ get_workspace_role=WorkspaceRepository(factory).get_account_role,get_visible_app_ids=None,))@@ -222,7 +222,7 @@ def _enable_visibility(management: _Management) -> None:)management.services.installed_apps.management = InstalledAppService(installed_apps=repository,- get_workspace_role=WorkspaceQueryRepository(management.session_factory).get_account_role,+ get_workspace_role=WorkspaceRepository(management.session_factory).get_account_role,get_visible_app_ids=access.get_visible_app_ids,)diff --git a/api/tests/unit_tests/controllers/console/test_apikey.py b/api/tests/unit_tests/controllers/console/test_apikey.pyindex a6bea948603..b58415d83ae 100644--- a/api/tests/unit_tests/controllers/console/test_apikey.py+++ b/api/tests/unit_tests/controllers/console/test_apikey.py@@ -26,7 +26,7 @@ from machinery.context import RequestContextfrom models.account import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccountRolefrom models.dataset import Datasetfrom models.model import ApiToken-from repositories.workspace_member_query_repository import WorkspaceMemberQueryRepository+from repositories.workspace.workspace_repository import WorkspaceRepositoryfrom services.app.api_key_service import AppApiKeyNotReadyErrorfrom services.auth.api_key_contracts import (ApiKeyLimitExceededError,@@ -286,7 +286,7 @@ def persisted_keys_app(sqlite_session.commit()dataset_access = build_dataset_dependencies(database_client=sqlite_session_factory,- workspace_roles=WorkspaceMemberQueryRepository(session_factory=sqlite_session_factory),+ workspace_roles=WorkspaceRepository(session_factory=sqlite_session_factory),).accessservice = build_dataset_api_key_service(database_client=sqlite_session_factory,diff --git a/api/tests/unit_tests/controllers/console/test_fastopenapi_setup.py b/api/tests/unit_tests/controllers/console/test_fastopenapi_setup.pyindex 19fa4f47089..e88463ccac0 100644--- a/api/tests/unit_tests/controllers/console/test_fastopenapi_setup.py+++ b/api/tests/unit_tests/controllers/console/test_fastopenapi_setup.py@@ -12,13 +12,8 @@ from controllers.console.error import AlreadySetupError, NotInitValidateErrorfrom dify_app import DifyAppfrom enums import DeploymentEditionfrom extensions import ext_fastopenapi-from services.setup_service import (- InitializationValidationRequiredError,- SetupAlreadyCompletedError,- SetupInput,- SetupService,- SetupStatus,-)+from services.account.contracts import SetupInput, SetupStatus+from services.setup_service import InitializationValidationRequiredError, SetupAlreadyCompletedError, SetupServiceif not hasattr(builtins, "MethodView"):builtins.MethodView = MethodView # type: ignore[attr-defined]diff --git a/api/tests/unit_tests/controllers/console/test_notification.py b/api/tests/unit_tests/controllers/console/test_notification.pyindex 8a37c06c1a0..129d27668f7 100644--- a/api/tests/unit_tests/controllers/console/test_notification.py+++ b/api/tests/unit_tests/controllers/console/test_notification.py@@ -5,13 +5,18 @@ from unittest.mock import Mock, patchimport pytestfrom flask import Flask+from controllers.console import flask_admission, wrapsfrom controllers.console.notification import (DismissNotificationPayload,NotificationApi,NotificationDismissApi,)+from enums import DeploymentEdition+from libs.login import AccountWithTenantfrom machinery.context import RequestContextfrom services.entities.notification_entities import NotificationItem, NotificationResult+from tests.unit_tests.config_override import apply_config_overrides+from tests.unit_tests.model_factories import make_accountdef _request_context() -> RequestContext:@@ -29,6 +34,7 @@ def _request_context() -> RequestContext:)def test_get_notification_validates_language_query_and_serializes_result(app: Flask,+ monkeypatch: pytest.MonkeyPatch,query_string: dict[str, str],expected_language: str,) -> None:@@ -49,14 +55,19 @@ def test_get_notification_validates_language_query_and_serializes_result()services = SimpleNamespace(notifications=service)api = NotificationApi()- method = api.get.__wrapped__context = _request_context()+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.CLOUD, LOGIN_DISABLED=True)+ identity = AccountWithTenant(account=make_account(), tenant_id=context.active_workspace_id)+ monkeypatch.setattr(wraps, "current_account_with_tenant", lambda: identity)+ monkeypatch.setattr(flask_admission, "current_account_with_tenant", lambda: identity)+ monkeypatch.setattr(flask_admission, "get_request_id", lambda: context.request_id)+ monkeypatch.setattr(flask_admission, "get_trace_id", lambda: context.trace_id)with (app.test_request_context("/notification", query_string=query_string),patch("controllers.console.notification.application_services", return_value=services),):- result, status = method(api, context)+ result, status = api.get()assert status == 200assert result == {diff --git a/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py b/api/tests/unit_tests/controllers/console/test_workflow_run_archive.pyindex 5b13c907f2d..ec4708ab40e 100644--- a/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py+++ b/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py@@ -51,7 +51,6 @@ def _original(method):def _admission_injector(method):- method = inspect.getclosurevars(method).nonlocals["admitted"]while "inject_request_context" not in method.__code__.co_qualname:method = method.__wrapped__return method@@ -101,12 +100,15 @@ def test_workflow_run_archive_endpoints_reject_non_manager_when_rbac_is_disabled(WorkflowRunArchiveDownloadFileApi.get, ("download-1",)),],)-def test_workflow_run_archive_endpoints_are_hidden_outside_cloud(+def test_workflow_run_archive_endpoints_reject_unsupported_edition_after_initialization(monkeypatch: pytest.MonkeyPatch,method,args: tuple[object, ...],) -> None:- apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY, LOGIN_DISABLED=True)+ monkeypatch.setattr("controllers.console.wraps._is_setup_completed", lambda: True)+ identity = AccountWithTenant(account=_account(TenantAccountRole.OWNER), tenant_id="tenant-1")+ monkeypatch.setattr("controllers.console.wraps.current_account_with_tenant", lambda: identity)app = Flask(__name__)with app.test_request_context(), pytest.raises(NotFound):diff --git a/api/tests/unit_tests/controllers/console/test_workspace_account.py b/api/tests/unit_tests/controllers/console/test_workspace_account.pyindex 8be7ec9dbc8..bd4e0b18f30 100644--- a/api/tests/unit_tests/controllers/console/test_workspace_account.py+++ b/api/tests/unit_tests/controllers/console/test_workspace_account.py@@ -29,7 +29,6 @@ from models import Account, AccountStatus, Tenant, TenantAccountJoinfrom models.account import TenantAccountRolefrom services import account_errorsfrom services.account_email import normalize_email-from services.account_service import AccountServicefrom services.entities.account_entities import AccountEducationActivation, ChangeEmailVerificationfrom services.entities.auth_entities import (ChangeEmailNewEmailToken,@@ -101,11 +100,11 @@ def _build_change_email_token("old_email": old_email,"code": code,}- if phase == AccountService.CHANGE_EMAIL_PHASE_OLD:+ if phase == "old_email":return ChangeEmailOldEmailToken(**token_kwargs)if phase == ChangeEmailPhase.OLD_EMAIL_VERIFIED:return ChangeEmailOldEmailVerifiedToken(**token_kwargs)- if phase == AccountService.CHANGE_EMAIL_PHASE_NEW:+ if phase == "new_email":return ChangeEmailNewEmailToken(**token_kwargs)if phase == ChangeEmailPhase.NEW_EMAIL_VERIFIED:return ChangeEmailNewEmailVerifiedToken(**token_kwargs)@@ -346,94 +345,6 @@ class TestChangeEmailControllers:)-class TestAccountServiceSendChangeEmailEmail:- """Service-level coverage for the phase-bound changes in `send_change_email_email`."""-- def test_should_raise_value_error_for_invalid_phase(self):- with pytest.raises(ValueError, match="phase must be one of"):- AccountService.send_change_email_email(- account=_build_account("[email protected]", "acc"),- email="[email protected]",- old_email="[email protected]",- phase="old_email_verified",- )-- @patch("services.account_service.send_change_mail_task")- @patch("services.account_service.AccountService.change_email_rate_limiter")- @patch("services.account_service.AccountService.generate_change_email_token")- def test_should_bind_account_id_and_target_email_into_generated_token(- self,- mock_generate_token: MagicMock,- mock_rate_limiter: MagicMock,- mock_mail_task: MagicMock,- ):- mock_rate_limiter.is_rate_limited.return_value = False- mock_generate_token.return_value = "the-token"- account = _build_account("[email protected]", "acc-123")-- returned = AccountService.send_change_email_email(- account=account,- email="[email protected]",- old_email="[email protected]",- language="en-US",- phase=AccountService.CHANGE_EMAIL_PHASE_NEW,- )-- assert returned == "the-token"- mock_generate_token.assert_called_once_with(- _build_change_email_token(- AccountService.CHANGE_EMAIL_PHASE_NEW,- account_id="acc-123",- email="[email protected]",- old_email="[email protected]",- code=mock_mail_task.delay.call_args.kwargs["code"],- ),- account,- )- mock_mail_task.delay.assert_called_once_with(- language="en-US",- to="[email protected]",- code=mock_mail_task.delay.call_args.kwargs["code"],- phase=AccountService.CHANGE_EMAIL_PHASE_NEW,- )- mock_rate_limiter.increment_rate_limit.assert_called_once_with("[email protected]")---class TestAccountServiceGetChangeEmailData:- @patch("services.account_service.TokenManager.get_token_data")- def test_should_parse_change_email_token_into_discriminated_union_model(self, mock_get_token_data):- mock_get_token_data.return_value = {- "token_type": "change_email",- "account_id": "acc-1",- "email": "[email protected]",- "old_email": "[email protected]",- "code": "654321",- "email_change_phase": ChangeEmailPhase.NEW_EMAIL_VERIFIED,- }-- token_data = AccountService.get_change_email_data("token-123")-- assert token_data == _build_change_email_token(- ChangeEmailPhase.NEW_EMAIL_VERIFIED,- account_id="acc-1",- email="[email protected]",- old_email="[email protected]",- code="654321",- )-- @patch("services.account_service.TokenManager.get_token_data")- def test_should_reject_change_email_token_without_account_id(self, mock_get_token_data):- mock_get_token_data.return_value = {- "token_type": "change_email",- "email": "[email protected]",- "old_email": "[email protected]",- "code": "654321",- "email_change_phase": AccountService.CHANGE_EMAIL_PHASE_NEW,- }-- assert AccountService.get_change_email_data("token-123") is None--class TestAccountDeletionFeedback:def test_delegates_feedback_to_application_service(self, app: Flask):deletion_feedback = MagicMock()@@ -497,20 +408,3 @@ class TestCheckEmailUnique:api = CheckEmailUnique()with pytest.raises(EmailDomainSuspendedError):inspect.unwrap(api.post)(api, CheckEmailUniquePayload.model_validate(request.get_json() or {}))--- "sqlite_session",- [(Account, Tenant, TenantAccountJoin)],- indirect=True,-)-def test_get_account_by_email_with_case_fallback_uses_lowercase_lookup(sqlite_session: Session):- expected_account, _ = _persist_account_with_tenant(- sqlite_session,- "[email protected]",- "case-fallback-account",- )-- result = AccountService.get_account_by_email_with_case_fallback("[email protected]", session=sqlite_session)-- assert result is expected_accountdiff --git a/api/tests/unit_tests/controllers/console/test_workspace_admission.py b/api/tests/unit_tests/controllers/console/test_workspace_admission.pynew file mode 100644index 00000000000..e83e14e4bab--- /dev/null+++ b/api/tests/unit_tests/controllers/console/test_workspace_admission.py@@ -0,0 +1,115 @@+"""Workspace admission composes existing checks before controller execution."""++from collections.abc import Callable+from unittest.mock import Mock++import pytest+from flask import Flask+from werkzeug.exceptions import Forbidden, NotFound, Unauthorized++from controllers.console import flask_admission, wraps+from controllers.console.error import NotInitValidateError, NotSetupError+from controllers.console.notification import NotificationApi+from controllers.console.workspace.error import AccountNotInitializedError+from controllers.console.workspace.workspace import WorkspacePermissionApi+from enums import DeploymentEdition+from libs import login as login_adapter+from libs.login import AccountWithTenant+from machinery.context import RequestContext+from models.account import Account, AccountStatus+from services.entities.feature_entities import FeatureModel+++def test_admin_key_admits_without_account_login(app: Flask, config_overrides: Callable[..., None]) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD, ADMIN_API_KEY="admin")++ class Handler:+ @flask_admission.console_admin_admission+ def get(self, *, page: int) -> int:+ return page++ with app.test_request_context(headers={"Authorization": "Bearer admin"}):+ assert Handler().get(page=2) == 2+ with app.test_request_context(), pytest.raises(Unauthorized):+ Handler().get(page=2)+++ ("edition", "enabled", "allowed"),+ [+ (DeploymentEdition.CLOUD, True, True),+ (DeploymentEdition.CLOUD, False, False),+ (DeploymentEdition.COMMUNITY, False, True),+ ],+)+def test_custom_brand_billing_admission(+ app: Flask,+ monkeypatch: pytest.MonkeyPatch,+ config_overrides: Callable[..., None],+ edition: DeploymentEdition,+ enabled: bool,+ allowed: bool,+) -> None:+ config_overrides(DEPLOYMENT_EDITION=edition)+ monkeypatch.setattr(flask_admission, "setup_required", lambda view: view)+ monkeypatch.setattr(flask_admission, "login_required", lambda view: view)+ monkeypatch.setattr(flask_admission, "account_initialization_required", lambda view: view)+ account = Account(name="User", email="[email protected]")+ identity = AccountWithTenant(account, "workspace")+ monkeypatch.setattr(flask_admission, "current_account_with_tenant", lambda: identity)+ monkeypatch.setattr(wraps, "current_account_with_tenant", lambda: identity)+ features = Mock(return_value=FeatureModel(can_replace_logo=enabled))+ monkeypatch.setattr(wraps.FeatureService, "get_features", features)+ reached = []++ class Handler:+ @flask_admission.console_account_admission(billing_resource="workspace_custom")+ def post(self, context: RequestContext) -> RequestContext:+ reached.append(context)+ return context++ with app.test_request_context():+ if allowed:+ context = Handler().post()+ assert isinstance(context, RequestContext)+ assert context.active_workspace_id == "workspace"+ else:+ with pytest.raises(Forbidden):+ Handler().post()+ assert bool(reached) is allowed+ assert features.call_count == int(edition == DeploymentEdition.CLOUD)++[email protected]("controller_type", [WorkspacePermissionApi, NotificationApi])+ ("setup_complete", "init_password", "status", "error"),+ [+ (False, "", None, NotSetupError),+ (False, "initial-password", None, NotInitValidateError),+ (True, "", None, Unauthorized),+ (True, "", AccountStatus.UNINITIALIZED, AccountNotInitializedError),+ (True, "", AccountStatus.ACTIVE, NotFound),+ ],+)+def test_account_admission_checks_identity_before_edition(+ app: Flask,+ monkeypatch: pytest.MonkeyPatch,+ config_overrides: Callable[..., None],+ controller_type: type[WorkspacePermissionApi] | type[NotificationApi],+ setup_complete: bool,+ init_password: str,+ status: AccountStatus | None,+ error: type[Exception],+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY, INIT_PASSWORD=init_password, LOGIN_DISABLED=False)+ monkeypatch.setattr(wraps, "_is_setup_completed", lambda: setup_complete)+ account = Account(name="User", email="[email protected]", status=status or AccountStatus.ACTIVE)+ identity = Mock(return_value=account, side_effect=Unauthorized() if status is None else None)+ monkeypatch.setattr(login_adapter, "_resolve_current_user", identity)+ monkeypatch.setattr(login_adapter, "check_csrf_token", Mock())+ monkeypatch.setattr(wraps, "current_account_with_tenant", lambda: AccountWithTenant(account, "workspace"))++ with app.test_request_context(), pytest.raises(error):+ controller_type().get()++ assert identity.call_count == int(setup_complete)diff --git a/api/tests/unit_tests/controllers/console/test_workspace_members.py b/api/tests/unit_tests/controllers/console/test_workspace_members.pydeleted file mode 100644index 0be530a33d6..00000000000--- a/api/tests/unit_tests/controllers/console/test_workspace_members.py+++ /dev/null@@ -1,183 +0,0 @@-from contextlib import nullcontext-from types import SimpleNamespace-from unittest.mock import ANY, patch--import pytest-from flask import Flask, g--from controllers.console.workspace.error import InvalidMemberRoleError-from controllers.console.workspace.members import MemberInviteEmailApi-from enums import DeploymentEdition-from models.account import Account, Tenant, TenantAccountRole-from tests.unit_tests.model_factories import make_tenant---def _tenant() -> Tenant:- return make_tenant(name="Test Tenant")---def app():- flask_app = Flask(__name__)- flask_app.config["TESTING"] = True- flask_app.login_manager = SimpleNamespace(load_user_from_request_context=lambda: None)- return flask_app---def _build_feature_flags():- placeholder_quota = SimpleNamespace(limit=0, size=0)- workspace_members = SimpleNamespace(enabled=False, is_available=lambda count: True)- return SimpleNamespace(- workspace_members=workspace_members,- members=placeholder_quota,- apps=placeholder_quota,- vector_space=placeholder_quota,- documents_upload_quota=placeholder_quota,- annotation_quota_limit=placeholder_quota,- )---class TestMemberInviteEmailApi:- @pytest.fixture(autouse=True)- def _member_config(self, config_overrides) -> None:- config_overrides(- RBAC_ENABLED=False,- CONSOLE_WEB_URL="https://console.example.com",- DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY,- )-- @pytest.fixture(autouse=True)- def _mock_member_invite_lock(self):- with patch("controllers.console.workspace.members.redis_client.lock", return_value=nullcontext()):- yield-- @patch("controllers.console.workspace.members.FeatureService.get_features")- @patch("controllers.console.workspace.members.RegisterService.invite_new_member")- @patch("controllers.console.wraps.db")- @patch("libs.login.check_csrf_token", return_value=None)- def test_invite_normalizes_emails(self, mock_csrf, mock_db, mock_invite_member, mock_get_features, app: Flask):- mock_get_features.return_value = _build_feature_flags()- mock_invite_member.return_value = "token-abc"-- tenant = _tenant()-- with (- patch("controllers.console.workspace.members._count_new_member_invites", return_value=(1, 1)),- ):- with app.test_request_context(- "/workspaces/current/members/invite-email",- method="POST",- json={"emails": ["[email protected]"], "role": TenantAccountRole.EDITOR.value, "language": "en-US"},- ):- account = Account(name="tester", email="[email protected]")- account._current_tenant = tenant- g._login_user = account- g._current_tenant = tenant- response, status_code = MemberInviteEmailApi().post()-- assert status_code == 201- assert response["invitation_results"][0]["email"] == "[email protected]"-- assert mock_invite_member.call_count == 1- call_args = mock_invite_member.call_args- assert call_args.kwargs["tenant"] == tenant- assert call_args.kwargs["email"] == "[email protected]"- assert call_args.kwargs["language"] == "en-US"- assert call_args.kwargs["role"] == TenantAccountRole.EDITOR- assert call_args.kwargs["inviter"] == account- mock_csrf.assert_called_once_with(ANY, account.id)-- @patch("controllers.console.workspace.members.FeatureService.get_features")- @patch("controllers.console.workspace.members.RegisterService.invite_new_member")- @patch("controllers.console.wraps.db")- @patch("libs.login.check_csrf_token", return_value=None)- def test_invite_rbac_enabled_accepts_rbac_role_id(- self,- mock_csrf,- mock_db,- mock_invite_member,- mock_get_features,- app,- config_overrides,- ):- """When RBAC is enabled, any non-empty role string should be accepted."""- config_overrides(RBAC_ENABLED=True)- mock_get_features.return_value = _build_feature_flags()- mock_invite_member.return_value = "rbac-token"-- tenant = _tenant()-- with app.test_request_context(- "/workspaces/current/members/invite-email",- method="POST",- json={"emails": ["[email protected]"], "role": "rbac-role-id-abc", "language": "en-US"},- ):- account = Account(name="tester", email="[email protected]")- account._current_tenant = tenant- g._login_user = account- g._current_tenant = tenant- response, status_code = MemberInviteEmailApi().post()-- assert status_code == 201- mock_invite_member.assert_called_once()- call_args = mock_invite_member.call_args- assert call_args.kwargs["role"] == "rbac-role-id-abc"-- @patch("controllers.console.workspace.members.FeatureService.get_features")- @patch("controllers.console.wraps.db")- @patch("libs.login.check_csrf_token", return_value=None)- def test_invite_rbac_disabled_rejects_invalid_role(- self,- mock_csrf,- mock_db,- mock_get_features,- app,- ):- """When RBAC is disabled, an invalid role string should be rejected."""- mock_get_features.return_value = _build_feature_flags()-- tenant = _tenant()-- with app.test_request_context(- "/workspaces/current/members/invite-email",- method="POST",- json={"emails": ["[email protected]"], "role": "invalid-role", "language": "en-US"},- ):- account = Account(name="tester", email="[email protected]")- account._current_tenant = tenant- g._login_user = account- g._current_tenant = tenant- with pytest.raises(InvalidMemberRoleError) as exc_info:- MemberInviteEmailApi().post()-- assert exc_info.value.error_code == "invalid_role"- assert exc_info.value.data == {"code": "invalid_role", "message": "Invalid role.", "status": 400}-- @patch("controllers.console.workspace.members.FeatureService.get_features")- @patch("controllers.console.wraps.db")- @patch("libs.login.check_csrf_token", return_value=None)- def test_invite_rbac_disabled_rejects_owner_role(- self,- mock_csrf,- mock_db,- mock_get_features,- app,- ):- """When RBAC is disabled, owner role should be rejected for invite."""- mock_get_features.return_value = _build_feature_flags()-- tenant = _tenant()-- with app.test_request_context(- "/workspaces/current/members/invite-email",- method="POST",- json={"emails": ["[email protected]"], "role": "owner", "language": "en-US"},- ):- account = Account(name="tester", email="[email protected]")- account._current_tenant = tenant- g._login_user = account- g._current_tenant = tenant- with pytest.raises(InvalidMemberRoleError) as exc_info:- MemberInviteEmailApi().post()-- assert exc_info.value.error_code == "invalid_role"diff --git a/api/tests/unit_tests/controllers/console/test_wraps.py b/api/tests/unit_tests/controllers/console/test_wraps.pyindex cb8f5a838a5..19d131268dd 100644--- a/api/tests/unit_tests/controllers/console/test_wraps.py+++ b/api/tests/unit_tests/controllers/console/test_wraps.py@@ -306,21 +306,6 @@ class TestCurrentContextInjection:assert admission_context.active_workspace_id == "tenant-123"assert route_value == "route-value"- def test_console_account_admission_enforces_declared_edition_first(self):- class Handler:- @flask_admission.console_account_admission(editions=frozenset({DeploymentEdition.CLOUD}))- def get(self, request_context: RequestContext):- return request_context-- with (- config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY),- Flask(__name__).test_request_context(),- pytest.raises(HTTPException) as exc_info,- ):- Handler().get()-- assert exc_info.value.code == 404-def test_console_account_admission_enforces_legacy_workspace_roles(self):current_user = make_account()current_user.role = TenantAccountRole.NORMALdiff --git a/api/tests/unit_tests/controllers/console/workspace/test_members.py b/api/tests/unit_tests/controllers/console/workspace/test_members.pyindex 20f9df2e652..1aa7ba76975 100644--- a/api/tests/unit_tests/controllers/console/workspace/test_members.py+++ b/api/tests/unit_tests/controllers/console/workspace/test_members.py@@ -1,14 +1,14 @@-from contextlib import nullcontext+from collections.abc import Callablefrom datetime import datetimefrom http import HTTPStatusfrom inspect import unwrapfrom typing import NamedTuple, override-from unittest.mock import MagicMock, patch+from unittest.mock import Mock, patchimport pytestfrom flask import Flask-from flask_restx import Resource-from sqlalchemy.orm import Session, scoped_session, sessionmaker+from flask_restx import Api, Resource+from werkzeug.exceptions import Forbidden, NotFoundfrom controllers.console.auth.error import (CannotTransferOwnerToSelfError,@@ -17,31 +17,42 @@ from controllers.console.auth.error import (InvalidTokenError,NotOwnerError,OwnerTransferLimitError,+ OwnerTransferRateLimitExceededError,+)+from controllers.console.auth.error import (+ MemberNotInTenantError as MemberNotInTenantRequestError,)from controllers.console.error import EmailSendIpLimitError, SeatsLimitExceeded, WorkspaceMembersLimitExceeded-from controllers.console.workspace.error import InvalidMemberRoleErrorfrom controllers.console.workspace.members import (DatasetOperatorMemberListApi,+ MemberCancelInviteApi,MemberInviteEmailApi,- MemberInviteErrorResponse,MemberListApi,MemberUpdateRoleApi,OwnerTransfer,OwnerTransferCheckApi,SendOwnerTransferEmailApi,- _count_new_member_invites,)-from enums import DeploymentEdition-from libs.external_api import ExternalApi+from libs.external_api import register_external_error_handlersfrom machinery.context import RequestContext-from models.account import Account, Tenant, TenantAccountJoin-from models.engine import db-from services.errors.account import AccountAlreadyInTenantError, SeatsLimitExceededError-from services.workspace_member_query_service import (- WorkspaceMemberQueryService,- WorkspaceMemberRole,- WorkspaceMemberSummary,+from services.account_errors import AccountNotFoundError+from services.errors.base import NoPermissionError+from services.errors.workspace import (+ CannotOperateSelfError,+ InvalidOwnerTransferCodeError,+ InvalidOwnerTransferEmailError,+ InvalidOwnerTransferTokenError,+ InvalidWorkspaceMemberRoleError,+ MemberNotInTenantError,+ OwnerTransferSendIPLimitedError,+ OwnerTransferSendRateLimitError,+ OwnerTransferVerificationLimitError,+ RoleAlreadyAssignedError,+ WorkspaceNotFoundError,+ WorkspaceNotLinkedError,)+from services.workspace.contracts import WorkspaceMemberRecord, WorkspaceMemberRole, WorkspaceMemberSummary+from services.workspace.member_service import WorkspaceMemberQueryService, WorkspaceMemberServiceclass _RecordingWorkspaceMemberQueryService(WorkspaceMemberQueryService):@@ -55,21 +66,12 @@ class _RecordingWorkspaceMemberQueryService(WorkspaceMemberQueryService):return self._result-class _ApplicationServicesStub(NamedTuple):- workspace_member_queries: WorkspaceMemberQueryService-+class _WorkspaceServicesStub(NamedTuple):+ member_queries: WorkspaceMemberQueryService-def _tenant(*, name: str = "Workspace") -> Tenant:- tenant = Tenant(name=name)- tenant.id = "t1"- return tenant--def _account(*, tenant: Tenant | None = None, account_id: str = "account-1", email: str = "[email protected]") -> Account:- account = Account(name="Test User", email=email)- account.id = account_id- account._current_tenant = tenant- return account+class _ApplicationServicesStub(NamedTuple):+ workspaces: _WorkspaceServicesStubclass TestMemberListApi:@@ -102,7 +104,7 @@ class TestMemberListApi:),))- application_services_stub = _ApplicationServicesStub(workspace_member_queries=workspace_member_queries)+ application_services_stub = _ApplicationServicesStub(_WorkspaceServicesStub(workspace_member_queries))with (app.test_request_context("/"),@@ -137,643 +139,305 @@ class TestMemberListApi:assert workspace_member_queries.contexts == [request_context]-class TestMemberInviteEmailApi:- @pytest.fixture(autouse=True)- def _invite_config(self, config_overrides) -> None:- config_overrides(- CONSOLE_WEB_URL="http://x",- DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY,- )-- @pytest.fixture(autouse=True)- def _mock_member_invite_lock(self):- with patch("controllers.console.workspace.members.redis_client.lock", return_value=nullcontext()):- yield-- @pytest.mark.parametrize("role", ["normal", "dataset_operator"])- def test_invite_success(self, app: Flask, config_overrides, role: str):- config_overrides(DATASET_OPERATOR_ENABLED=True)- api = MemberInviteEmailApi()- method = unwrap(api.post)-- tenant = _tenant()- user = _account(tenant=tenant)- features = MagicMock()- features.workspace_members.enabled = False- features.workspace_members.is_available.return_value = True-- payload = {- "emails": ["[email protected]", "[email protected]"],- "role": role,- "language": "en-US",- }-- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.FeatureService.get_features", return_value=features),- patch("controllers.console.workspace.members._count_new_member_invites", return_value=(1, 1)) as mock_count,- patch(- "controllers.console.workspace.members.RegisterService.invite_new_member", return_value="token"- ) as mock_invite,- ):- result, status = method(api, user)-- assert status == 201- assert result["result"] == "success"- assert result["invitation_results"][0]["email"] == "[email protected]"- mock_count.assert_not_called()- mock_invite.assert_called_once()- assert mock_invite.call_args.kwargs["email"] == "[email protected]"- assert mock_invite.call_args.kwargs["role"] == role-- def test_invite_limit_exceeded(self, app: Flask, config_overrides):- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- api = MemberInviteEmailApi()- method = unwrap(api.post)-- tenant = _tenant()- user = _account(tenant=tenant)- features = MagicMock()- features.workspace_members.enabled = True- features.workspace_members.is_available.return_value = False-- payload = {- "emails": ["[email protected]"],- "role": "normal",- }-- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.FeatureService.get_features", return_value=features),- patch("controllers.console.workspace.members._count_new_member_invites", return_value=(1, 1)),- ):- with pytest.raises(WorkspaceMembersLimitExceeded):- method(api, user)-- def test_invite_cloud_member_limit_exceeded(self, app: Flask, config_overrides):- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)- api = MemberInviteEmailApi()- method = unwrap(api.post)-- tenant = _tenant()- user = _account(tenant=tenant)- features = MagicMock()- features.members.size = 9- features.members.limit = 10- features.workspace_members.enabled = False-- payload = {- "emails": ["[email protected]", "[email protected]"],- "role": "normal",- }-- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.FeatureService.get_features", return_value=features),- patch("controllers.console.workspace.members._count_new_member_invites", return_value=(2, 2)),- patch("controllers.console.workspace.members._count_current_members", return_value=9),- ):- with pytest.raises(WorkspaceMembersLimitExceeded):- method(api, user)-- def test_invite_already_member(self, app: Flask):- api = MemberInviteEmailApi()- method = unwrap(api.post)-- tenant = _tenant()- user = _account(tenant=tenant)- features = MagicMock()- features.workspace_members.enabled = False- features.workspace_members.is_available.return_value = True-- payload = {- "emails": ["[email protected]"],- "role": "normal",- }-- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.FeatureService.get_features", return_value=features),- patch("controllers.console.workspace.members._count_new_member_invites", return_value=(0, 0)),- patch(- "controllers.console.workspace.members.RegisterService.invite_new_member",- side_effect=AccountAlreadyInTenantError(),- ),- ):- result, status = method(api, user)-- assert status == 201- assert result["invitation_results"][0]["status"] == "already_member"- assert result["invitation_results"][0]["message"] == "Account already in workspace."-- @pytest.mark.parametrize("role", ["owner", "dataset_operator"])- def test_invite_invalid_role(self, app: Flask, config_overrides, role: str):- config_overrides(DATASET_OPERATOR_ENABLED=False)- api = MemberInviteEmailApi()- method = unwrap(api.post)-- payload = {- "emails": ["[email protected]"],- "role": role,- }-- with app.test_request_context("/", json=payload):- with pytest.raises(InvalidMemberRoleError) as exc_info:- method(api, _account(tenant=_tenant()))-- assert exc_info.value.error_code == "invalid_role"-- def test_invite_invalid_payload_matches_documented_error_response(self):- app = Flask(__name__)- api = ExternalApi(app)- method = unwrap(MemberInviteEmailApi.post)- current_user = _account()-- @api.route("/workspaces/current/members/invite-email")- class MemberInviteValidationApi(Resource):- def post(self):- return method(MemberInviteEmailApi(), current_user)-- response = app.test_client().post(- "/workspaces/current/members/invite-email",- json={"emails": [], "role": "normal"},- )-- assert response.status_code == 400- error = MemberInviteErrorResponse.model_validate(response.get_json())- assert error.code == "invalid_param"-- def test_invite_generic_exception(self, app: Flask):- api = MemberInviteEmailApi()- method = unwrap(api.post)-- tenant = _tenant()- user = _account(tenant=tenant)- features = MagicMock()- features.workspace_members.enabled = False- features.workspace_members.is_available.return_value = True-- payload = {- "emails": ["[email protected]"],- "role": "normal",- }-- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.FeatureService.get_features", return_value=features),- patch("controllers.console.workspace.members._count_new_member_invites", return_value=(1, 1)),- patch(- "controllers.console.workspace.members.RegisterService.invite_new_member",- side_effect=Exception("boom"),- ),- ):- result, _ = method(api, user)-- assert result["invitation_results"][0]["status"] == "failed"-- def test_invite_seats_limit_exceeded(self, app: Flask, config_overrides):- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- api = MemberInviteEmailApi()- method = unwrap(api.post)-- tenant = _tenant()- user = _account(tenant=tenant)- features = MagicMock()- features.workspace_members.enabled = False- license_info = MagicMock()- license_info.seats.is_available.return_value = False-- payload = {- "emails": ["[email protected]", "[email protected]"],- "role": "normal",- }-- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.FeatureService.get_features", return_value=features),- patch("controllers.console.workspace.members._count_new_member_invites", return_value=(2, 2)),- patch(- "controllers.console.workspace.members.SystemFeatureService.get_license",- return_value=license_info,- ) as mock_get_license,- patch("controllers.console.workspace.members.RegisterService.invite_new_member") as mock_invite,- ):- with pytest.raises(SeatsLimitExceeded):- method(api, user)-- mock_get_license.assert_called_once_with()- license_info.seats.is_available.assert_called_once_with(2)- mock_invite.assert_not_called()-- def test_invite_existing_accounts_do_not_consume_seats(self, app: Flask, config_overrides):- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- api = MemberInviteEmailApi()- method = unwrap(api.post)-- tenant = _tenant()- user = _account(tenant=tenant)- features = MagicMock()- features.workspace_members.enabled = False- license_info = MagicMock()- license_info.seats.is_available.return_value = False-- payload = {- "emails": ["[email protected]", "[email protected]"],- "role": "normal",- }-- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.FeatureService.get_features", return_value=features),- patch("controllers.console.workspace.members._count_new_member_invites", return_value=(2, 0)),- patch(- "controllers.console.workspace.members.SystemFeatureService.get_license",- return_value=license_info,- ) as mock_get_license,- patch(- "controllers.console.workspace.members.RegisterService.invite_new_member", return_value="token"- ) as mock_invite,- ):- result, status = method(api, user)-- assert status == 201- assert len(result["invitation_results"]) == 2- mock_get_license.assert_not_called()- license_info.seats.is_available.assert_not_called()- assert mock_invite.call_count == 2-- def test_invite_mixed_accounts_with_available_seats(self, app: Flask, config_overrides):- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- api = MemberInviteEmailApi()- method = unwrap(api.post)-- tenant = _tenant()- user = _account(tenant=tenant)- features = MagicMock()- features.workspace_members.enabled = False- license_info = MagicMock()- license_info.seats.is_available.return_value = True-- payload = {- "emails": ["[email protected]", "[email protected]"],- "role": "normal",- }-- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.FeatureService.get_features", return_value=features),- patch("controllers.console.workspace.members._count_new_member_invites", return_value=(2, 1)),- patch(- "controllers.console.workspace.members.SystemFeatureService.get_license",- return_value=license_info,- ) as mock_get_license,- patch(- "controllers.console.workspace.members.RegisterService.invite_new_member", return_value="token"- ) as mock_invite,- ):- result, status = method(api, user)-- assert status == 201- assert len(result["invitation_results"]) == 2- mock_get_license.assert_called_once_with()- license_info.seats.is_available.assert_called_once_with(1)- assert mock_invite.call_count == 2-- def test_invite_skips_seats_limit_when_enterprise_disabled(self, app: Flask):- api = MemberInviteEmailApi()- method = unwrap(api.post)-- tenant = _tenant()- user = _account(tenant=tenant)- features = MagicMock()- features.workspace_members.enabled = False- license_info = MagicMock()- license_info.seats.is_available.return_value = False-- payload = {- "emails": ["[email protected]"],- "role": "normal",+def services(monkeypatch: pytest.MonkeyPatch) -> Mock:+ from extensions.application_services.workspace import WorkspaceServices+ from extensions.ext_application_services import AccountServices, ApplicationServices+ from services.workspace.member_service import WorkspaceInvitationService, WorkspaceOwnerTransferService++ services = Mock(spec=ApplicationServices)+ services.accounts = Mock(spec=AccountServices)+ services.workspaces = Mock(spec=WorkspaceServices)+ services.workspaces.invitations = Mock(spec=WorkspaceInvitationService)+ services.workspaces.owner_transfer = Mock(spec=WorkspaceOwnerTransferService)+ services.workspaces.members = Mock(spec=WorkspaceMemberService)+ services.workspaces.member_queries = Mock(spec=WorkspaceMemberQueryService)+ import importlib++ monkeypatch.setattr(+ importlib.import_module("controllers.console.workspace.members"), "application_services", lambda: services+ )+ return services++[email protected]("operation", ["remove", "update_role"])+def test_member_mutation_delegates_admitted_ids(app: Flask, services: Mock, operation: str) -> None:+ context = RequestContext("request", None, "actor", "workspace")+ with app.test_request_context("/", json={"role": "editor"}):+ if operation == "remove":+ api = MemberCancelInviteApi()+ response, status = unwrap(api.delete)(api, context, "member")+ assert status == 200+ assert response == {"result": "success", "tenant_id": "workspace"}+ services.workspaces.members.remove.assert_called_once_with("workspace", "member", "actor")+ else:+ api = MemberUpdateRoleApi()+ assert unwrap(api.put)(api, context, "member") == {"result": "success"}+ services.workspaces.members.update_role.assert_called_once_with("workspace", "member", "editor", "actor")++[email protected]("operation", ["remove", "update_role"])+ ("error", "code", "status"),+ [+ (CannotOperateSelfError("self"), "cannot-operate-self", 400),+ (NoPermissionError("denied"), "forbidden", 403),+ (MemberNotInTenantError("missing"), "member-not-found", 404),+ ],+)+def test_member_mutation_maps_errors(+ app: Flask, services: Mock, operation: str, error: Exception, code: str, status: int+) -> None:+ service_method = (+ services.workspaces.members.remove if operation == "remove" else services.workspaces.members.update_role+ )+ service_method.side_effect = error+ api = MemberCancelInviteApi() if operation == "remove" else MemberUpdateRoleApi()+ method = api.delete if isinstance(api, MemberCancelInviteApi) else api.put+ with app.test_request_context("/", json={"role": "editor"}):+ result = unwrap(method)(api, RequestContext("request", None, "actor", "workspace"), "member")+ assert result == ({"code": code, "message": str(error)}, status)++[email protected]("operation", ["remove", "update_role"])+def test_member_mutation_maps_missing_account(app: Flask, services: Mock, operation: str) -> None:+ service_method = (+ services.workspaces.members.remove if operation == "remove" else services.workspaces.members.update_role+ )+ service_method.side_effect = AccountNotFoundError()+ api = MemberCancelInviteApi() if operation == "remove" else MemberUpdateRoleApi()+ method = api.delete if isinstance(api, MemberCancelInviteApi) else api.put+ with app.test_request_context("/", json={"role": "editor"}), pytest.raises(NotFound):+ unwrap(method)(api, RequestContext("request", None, "actor", "workspace"), "missing")+++ ("error", "code", "message"),+ [+ (InvalidWorkspaceMemberRoleError(), "invalid-role", "Invalid role"),+ (RoleAlreadyAssignedError("unchanged"), "role-already-assigned", "unchanged"),+ ],+)+def test_update_role_maps_role_errors(app: Flask, services: Mock, error: Exception, code: str, message: str) -> None:+ services.workspaces.members.update_role.side_effect = error+ api = MemberUpdateRoleApi()+ with app.test_request_context("/", json={"role": "editor"}):+ result = unwrap(api.put)(api, RequestContext("request", None, "actor", "workspace"), "member")+ assert result == ({"code": code, "message": message}, 400)+++def test_dataset_operator_list_uses_admitted_workspace(app: Flask, services: Mock) -> None:+ services.workspaces.member_queries.list_members.return_value = ()+ api = DatasetOperatorMemberListApi()+ with app.test_request_context("/"):+ result = unwrap(api.get)(api, RequestContext("request", None, "actor", "workspace"))+ assert result == ({"accounts": []}, 200)+ services.workspaces.member_queries.list_members.assert_called_once_with("workspace", dataset_operators_only=True)+++def test_dataset_operator_list_serializes_membership_snapshot(app: Flask, services: Mock) -> None:+ timestamp = datetime(2026, 1, 1)+ services.workspaces.member_queries.list_members.return_value = (+ WorkspaceMemberRecord(+ id="operator",+ name="Operator",+ email="[email protected]",+ avatar=None,+ last_login_at=None,+ last_active_at=timestamp,+ created_at=timestamp,+ status="active",+ legacy_role="dataset_operator",+ ),+ )+ api = DatasetOperatorMemberListApi()+ with app.test_request_context("/"):+ result, status = unwrap(api.get)(api, RequestContext("request", None, "actor", "workspace"))+ assert status == 200+ assert result["accounts"] == [+ {+ "id": "operator",+ "name": "Operator",+ "email": "[email protected]",+ "avatar": None,+ "avatar_url": None,+ "last_login_at": None,+ "last_active_at": int(timestamp.timestamp()),+ "created_at": int(timestamp.timestamp()),+ "role": "dataset_operator",+ "roles": [],+ "status": "active",}+ ]- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.FeatureService.get_features", return_value=features),- patch("controllers.console.workspace.members._count_new_member_invites", return_value=(1, 1)),- patch(- "controllers.console.workspace.members.SystemFeatureService.get_license",- return_value=license_info,- ) as mock_get_license,- patch("controllers.console.workspace.members.RegisterService.invite_new_member", return_value="token"),- ):- result, status = method(api, user)-- assert status == 201- assert result["invitation_results"][0]["status"] == "success"- mock_get_license.assert_not_called()- license_info.seats.is_available.assert_not_called()- def test_invite_seats_error_is_reported_as_failed_result(self, app: Flask, config_overrides):- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)+def test_invitation_policy_denial_preserves_http_status(app: Flask, services: Mock) -> None:+ services.workspaces.invitations.invite_many.side_effect = NoPermissionError(+ "Workspace policy prohibits member invitations"+ )+ api = MemberInviteEmailApi()+ with (+ app.test_request_context("/", method="POST", json={"emails": ["[email protected]"], "role": "normal"}),+ pytest.raises(Forbidden, match="Workspace policy prohibits member invitations"),+ ):+ unwrap(api.post)(api, RequestContext("request", None, "owner", "workspace"))+++def test_bulk_invite_serializes_results_and_normalizes_input(app: Flask, services: Mock) -> None:+ from services.workspace.contracts import WorkspaceInvitationResult++ services.workspaces.invitations.invite_many.return_value = (+ WorkspaceInvitationResult("[email protected]", "success", token="token"),+ WorkspaceInvitationResult("[email protected]", "already_member", message="Account already in workspace."),+ WorkspaceInvitationResult("[email protected]", "failed", message="Registration failed"),+ )+ context = RequestContext("request", None, "owner", "workspace")+ with app.test_request_context(+ "/",+ method="POST",+ json={"emails": ["[email protected]", "[email protected]", "[email protected]", "[email protected]"], "role": "normal"},+ ):api = MemberInviteEmailApi()- method = unwrap(api.post)-- tenant = _tenant()- user = _account(tenant=tenant)- features = MagicMock()- features.workspace_members.enabled = False- license_info = MagicMock()- license_info.seats.is_available.return_value = True-- payload = {- "emails": ["[email protected]"],- "role": "normal",- }-- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.FeatureService.get_features", return_value=features),- patch("controllers.console.workspace.members._count_new_member_invites", return_value=(1, 1)),- patch(- "controllers.console.workspace.members.SystemFeatureService.get_license",- return_value=license_info,- ),- patch(- "controllers.console.workspace.members.RegisterService.invite_new_member",- side_effect=SeatsLimitExceededError("licensed seats limit exceeded"),- ),- ):- result, status = method(api, user)-- assert status == 201- assert result["invitation_results"][0]["status"] == "failed"- assert result["invitation_results"][0]["message"] == "licensed seats limit exceeded"---class TestCountNewMemberInvites:- def test_count_new_member_invites(- self, monkeypatch: pytest.MonkeyPatch, sqlite_session_factory: sessionmaker[Session]+ result, status = unwrap(api.post)(api, context)+ assert status == 201+ assert result["tenant_id"] == "workspace"+ assert [item["status"] for item in result["invitation_results"]] == ["success", "already_member", "failed"]+ assert "email=a%40example.com&token=token" in result["invitation_results"][0]["url"]+ services.workspaces.invitations.invite_many.assert_called_once_with(+ context, emails=["[email protected]", "[email protected]", "[email protected]"], language=None, role="normal"+ )++[email protected](("seats", "expected"), [(True, SeatsLimitExceeded), (False, WorkspaceMembersLimitExceeded)])+def test_invite_maps_capacity_error(app: Flask, services: Mock, seats: bool, expected: type[Exception]) -> None:+ from services.errors.workspace import WorkspaceInvitationQuotaError++ services.workspaces.invitations.invite_many.side_effect = WorkspaceInvitationQuotaError(seats=seats)+ api = MemberInviteEmailApi()+ with (+ app.test_request_context("/", method="POST", json={"emails": ["[email protected]"], "role": "normal"}),+ pytest.raises(expected),):- new_account = None- existing_account_not_in_tenant = Account(name="External", email="[email protected]")- existing_account_not_in_tenant.id = "account-2"- existing_account_in_tenant = Account(name="Member", email="[email protected]")- existing_account_in_tenant.id = "account-3"- database_session = scoped_session(sqlite_session_factory)- monkeypatch.setattr(db, "session", database_session)- database_session.add(- TenantAccountJoin(- tenant_id="tenant-1",- account_id="account-3",- current=True,- role="normal",- )- )- database_session.commit()-- with patch(- "controllers.console.workspace.members.AccountService.get_account_by_email_with_case_fallback",- side_effect=[new_account, existing_account_not_in_tenant, existing_account_in_tenant],- ) as mock_get_account:- result = _count_new_member_invites(- "tenant-1",- )-- assert result == (2, 1)- assert mock_get_account.call_count == 3- database_session.remove()---class TestMemberUpdateRoleApi:- @pytest.mark.parametrize("role", ["invalid-role", "dataset_operator"])- def test_update_invalid_role(self, app: Flask, config_overrides, role: str):- config_overrides(DATASET_OPERATOR_ENABLED=False)- api = MemberUpdateRoleApi()- method = unwrap(api.put)-- payload = {"role": role}-- with app.test_request_context("/", json=payload):- result, status = method(api, _account(tenant=_tenant()), "id")-- assert status == 400---class TestDatasetOperatorMemberListApi:- def test_get_success(self, app: Flask):- api = DatasetOperatorMemberListApi()- method = unwrap(api.get)-- tenant = _tenant()- user = _account(tenant=tenant)- member = MagicMock()- member.id = "op1"- member.name = "Operator"- member.email = "[email protected]"- member.avatar = "avatar.png"- member.role = "operator"- member.status = "active"- members = [member]-- with (- app.test_request_context("/"),- patch(- "controllers.console.workspace.members.TenantService.get_dataset_operator_members", return_value=members- ),- ):- result, status = method(api, user)-- assert status == 200- assert len(result["accounts"]) == 1-- def test_get_no_tenant(self, app: Flask):- api = DatasetOperatorMemberListApi()- method = unwrap(api.get)-- user = _account(tenant=None)-- with (- app.test_request_context("/"),- ):- with pytest.raises(ValueError):- method(api, user)---class TestSendOwnerTransferEmailApi:- def test_send_success(self, app: Flask):- api = SendOwnerTransferEmailApi()- method = unwrap(api.post)-- tenant = _tenant(name="ws")- user = _account(tenant=tenant, email="[email protected]")-- payload = {}-- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.extract_remote_ip", return_value="1.1.1.1"),- patch("controllers.console.workspace.members.AccountService.is_email_send_ip_limit", return_value=False),- patch("controllers.console.workspace.members.TenantService.is_owner", return_value=True),- patch(- "controllers.console.workspace.members.AccountService.send_owner_transfer_email", return_value="token"- ),- ):- result = method(api, user)-- assert result["result"] == "success"-- def test_send_ip_limit(self, app: Flask):- api = SendOwnerTransferEmailApi()- method = unwrap(api.post)-- payload = {}-- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.extract_remote_ip", return_value="1.1.1.1"),- patch("controllers.console.workspace.members.AccountService.is_email_send_ip_limit", return_value=True),- ):- with pytest.raises(EmailSendIpLimitError):- method(api, _account())-- def test_send_not_owner(self, app: Flask):- api = SendOwnerTransferEmailApi()- method = unwrap(api.post)-- tenant = _tenant()- user = _account(tenant=tenant)-- with (- app.test_request_context("/", json={}),- patch("controllers.console.workspace.members.extract_remote_ip", return_value="1.1.1.1"),- patch("controllers.console.workspace.members.AccountService.is_email_send_ip_limit", return_value=False),- patch("controllers.console.workspace.members.TenantService.is_owner", return_value=False),- ):- with pytest.raises(NotOwnerError):- method(api, user)---class TestOwnerTransferCheckApi:- def test_check_invalid_code(self, app: Flask):- api = OwnerTransferCheckApi()- method = unwrap(api.post)-- tenant = _tenant()- user = _account(tenant=tenant, email="[email protected]")-- payload = {"code": "x", "token": "t"}-- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.TenantService.is_owner", return_value=True),- patch(- "controllers.console.workspace.members.AccountService.is_owner_transfer_error_rate_limit",- return_value=False,- ),- patch(- "controllers.console.workspace.members.AccountService.get_owner_transfer_data",- return_value={"email": "[email protected]", "code": "y"},- ),- ):- with pytest.raises(EmailCodeError):- method(api, user)-- def test_rate_limited(self, app: Flask):- api = OwnerTransferCheckApi()- method = unwrap(api.post)-- tenant = _tenant()- user = _account(tenant=tenant, email="[email protected]")-- payload = {"code": "x", "token": "t"}-- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.TenantService.is_owner", return_value=True),- patch(- "controllers.console.workspace.members.AccountService.is_owner_transfer_error_rate_limit",- return_value=True,- ),- ):- with pytest.raises(OwnerTransferLimitError):- method(api, user)-- def test_invalid_token(self, app: Flask):- api = OwnerTransferCheckApi()- method = unwrap(api.post)-- tenant = _tenant()- user = _account(tenant=tenant, email="[email protected]")-- payload = {"code": "x", "token": "t"}+ unwrap(api.post)(api, RequestContext("request", None, "owner", "workspace"))+++ ("error", "expected"),+ [+ (NoPermissionError(), NotOwnerError),+ (AccountNotFoundError(), NotFound),+ (WorkspaceNotFoundError(), NotFound),+ (OwnerTransferSendIPLimitedError(), EmailSendIpLimitError),+ (OwnerTransferSendRateLimitError(3), OwnerTransferRateLimitExceededError),+ (OwnerTransferVerificationLimitError(), OwnerTransferLimitError),+ (InvalidOwnerTransferTokenError(), InvalidTokenError),+ (InvalidOwnerTransferEmailError(), InvalidEmailError),+ (InvalidOwnerTransferCodeError(), EmailCodeError),+ (CannotOperateSelfError(), CannotTransferOwnerToSelfError),+ (MemberNotInTenantError(), MemberNotInTenantRequestError),+ ],+)+def test_owner_verification_maps_errors(+ app: Flask, services: Mock, error: Exception, expected: type[Exception]+) -> None:+ services.workspaces.owner_transfer.verify_code.side_effect = error+ api = OwnerTransferCheckApi()+ with (+ app.test_request_context("/", method="POST", json={"token": "token", "code": "123456"}),+ pytest.raises(expected) as raised,+ ):+ unwrap(api.post)(api, RequestContext("request", None, "owner", "workspace"))+ assert raised.value.__cause__ is error+ if isinstance(error, OwnerTransferSendRateLimitError):+ assert "3" in str(raised.value)- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.TenantService.is_owner", return_value=True),- patch(- "controllers.console.workspace.members.AccountService.is_owner_transfer_error_rate_limit",- return_value=False,- ),- patch("controllers.console.workspace.members.AccountService.get_owner_transfer_data", return_value=None),- ):- with pytest.raises(InvalidTokenError):- method(api, user)- def test_invalid_email(self, app: Flask):+def test_owner_verification_serializes_promoted_token(app: Flask, services: Mock) -> None:+ services.workspaces.owner_transfer.verify_code.return_value = ("[email protected]", "promoted")+ with app.test_request_context("/", method="POST", json={"token": "token", "code": "123456"}):api = OwnerTransferCheckApi()- method = unwrap(api.post)-- tenant = _tenant()- user = _account(tenant=tenant, email="[email protected]")-- payload = {"code": "x", "token": "t"}-- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.TenantService.is_owner", return_value=True),- patch(- "controllers.console.workspace.members.AccountService.is_owner_transfer_error_rate_limit",- return_value=False,- ),- patch(- "controllers.console.workspace.members.AccountService.get_owner_transfer_data",- return_value={"email": "[email protected]", "code": "x"},- ),- ):- with pytest.raises(InvalidEmailError):- method(api, user)---class TestOwnerTransferApi:- def test_transfer_self(self, app: Flask):- api = OwnerTransfer()- method = unwrap(api.post)-- tenant = _tenant()- user = _account(tenant=tenant, account_id="1", email="[email protected]")-- payload = {"token": "t"}-- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.TenantService.is_owner", return_value=True),- ):- with pytest.raises(CannotTransferOwnerToSelfError):- method(api, user, "1")-- def test_invalid_token(self, app: Flask):- api = OwnerTransfer()- method = unwrap(api.post)-- tenant = _tenant()- user = _account(tenant=tenant, account_id="1", email="[email protected]")-- payload = {"token": "t"}-- with (- app.test_request_context("/", json=payload),- patch("controllers.console.workspace.members.TenantService.is_owner", return_value=True),- patch("controllers.console.workspace.members.AccountService.get_owner_transfer_data", return_value=None),- ):- with pytest.raises(InvalidTokenError):- method(api, user, "2")+ response = unwrap(api.post)(api, RequestContext("request", None, "owner", "workspace"))+ assert response == {"is_valid": True, "email": "[email protected]", "token": "promoted"}+++ ("service_method", "resource_type", "handler", "has_member_id"),+ [+ pytest.param(+ lambda services: services.workspaces.members.remove,+ MemberCancelInviteApi,+ MemberCancelInviteApi.delete,+ True,+ id="remove",+ ),+ pytest.param(+ lambda services: services.workspaces.members.update_role,+ MemberUpdateRoleApi,+ MemberUpdateRoleApi.put,+ True,+ id="update_role",+ ),+ pytest.param(+ lambda services: services.workspaces.owner_transfer.send_code,+ SendOwnerTransferEmailApi,+ SendOwnerTransferEmailApi.post,+ False,+ id="send_code",+ ),+ pytest.param(+ lambda services: services.workspaces.owner_transfer.verify_code,+ OwnerTransferCheckApi,+ OwnerTransferCheckApi.post,+ False,+ id="verify_code",+ ),+ pytest.param(+ lambda services: services.workspaces.owner_transfer.transfer,+ OwnerTransfer,+ OwnerTransfer.post,+ True,+ id="transfer",+ ),+ ],+)+ ("error", "status", "code"),+ [+ (RuntimeError("backend unavailable"), 500, "unknown"),+ (WorkspaceNotLinkedError("unmapped workspace failure"), 500, "unknown"),+ (WorkspaceNotFoundError(), 404, "not_found"),+ (AccountNotFoundError(), 404, "not_found"),+ ],+)+def test_member_errors_reach_the_http_boundary(+ services: Mock,+ service_method: Callable[[Mock], Mock],+ resource_type: type[Resource],+ handler: Callable[..., object],+ has_member_id: bool,+ error: Exception,+ status: int,+ code: str,+) -> None:+ service_method(services).side_effect = error+ resource = resource_type()+ method = unwrap(handler)+ context = RequestContext("request", None, "owner", "workspace")+ http_app = Flask(__name__)+ http_api = Api(http_app, doc=False)+ register_external_error_handlers(http_api)++ class Endpoint(Resource):+ def post(self) -> object:+ if has_member_id:+ return method(resource, context, "member")+ return method(resource, context)++ http_api.add_resource(Endpoint, "/members")+ response = http_app.test_client().post("/members", json={"role": "editor", "token": "token", "code": "123456"})+ assert response.status_code == status+ payload = response.get_json()+ assert isinstance(payload, dict)+ assert payload["code"] == code+ if status == 500:+ assert payload["message"] == "Internal Server Error"diff --git a/api/tests/unit_tests/controllers/console/workspace/test_model_providers.py b/api/tests/unit_tests/controllers/console/workspace/test_model_providers.pyindex 2af0ce3db7a..dd247132ec2 100644--- a/api/tests/unit_tests/controllers/console/workspace/test_model_providers.py+++ b/api/tests/unit_tests/controllers/console/workspace/test_model_providers.py@@ -6,7 +6,6 @@ from unittest.mock import patchimport pytestfrom flask import Flask, g, requestfrom pydantic_core import ValidationError-from sqlalchemy.orm import Sessionfrom werkzeug.exceptions import Forbidden, UnprocessableEntityfrom configs import dify_config@@ -48,7 +47,7 @@ from services.entities.model_provider_entities import (ProviderResponse,SystemConfigurationResponse,)-from services.workspace_service import EffectiveCreditPool+from services.workspace.contracts import EffectiveCreditPoolfrom tests.unit_tests.config_override import config_overrides_contextVALID_UUID = "123e4567-e89b-12d3-a456-426614174000"@@ -252,10 +251,9 @@ class TestModelProviderSummaryListApi:class TestModelProviderCreditsApi:- def test_get_success(self, unbound_session: Session):+ def test_get_success(self) -> None:api = ModelProviderCreditsApi()method = unwrap(api.get)- session = unbound_sessioncredit_pool = EffectiveCreditPool(plan="team",pool_type="paid",@@ -265,12 +263,13 @@ class TestModelProviderCreditsApi:)with patch(- "controllers.console.workspace.model_providers.WorkspaceService.get_effective_credit_pool",- return_value=credit_pool,- ) as get_effective_credit_pool:- result = method(api, session, "tenant1")+ "controllers.console.workspace.model_providers.application_services",+ ) as services:+ get_effective_credit_pool = services.return_value.workspaces.management.get_effective_credit_pool+ get_effective_credit_pool.return_value = credit_pool+ result = method(api, "tenant1")- get_effective_credit_pool.assert_called_once_with("tenant1", session=session)+ get_effective_credit_pool.assert_called_once_with("tenant1")assert result == {"pool_type": "paid","quota_limit": -1,@@ -282,16 +281,15 @@ class TestModelProviderCreditsApi:"next_credit_reset_date": 1775001600,}- def test_get_without_effective_pool(self, unbound_session: Session):+ def test_get_without_effective_pool(self) -> None:api = ModelProviderCreditsApi()method = unwrap(api.get)- session = unbound_sessionwith patch(- "controllers.console.workspace.model_providers.WorkspaceService.get_effective_credit_pool",- return_value=EffectiveCreditPool(),- ):- result = method(api, session, "tenant1")+ "controllers.console.workspace.model_providers.application_services",+ ) as services:+ services.return_value.workspaces.management.get_effective_credit_pool.return_value = EffectiveCreditPool()+ result = method(api, "tenant1")assert result == {"pool_type": None,diff --git a/api/tests/unit_tests/controllers/console/workspace/test_workspace.py b/api/tests/unit_tests/controllers/console/workspace/test_workspace.pyindex 2bf35fc6917..698306c15af 100644--- a/api/tests/unit_tests/controllers/console/workspace/test_workspace.py+++ b/api/tests/unit_tests/controllers/console/workspace/test_workspace.py@@ -1,20 +1,18 @@-import logging-from collections.abc import Iterator-from datetime import timedelta+"""Controller contracts: parsing, delegation, serialization and HTTP errors."""++from collections.abc import Callable+from dataclasses import dataclass+from datetime import datetimefrom http import HTTPStatusfrom inspect import unwrapfrom io import BytesIO-from types import SimpleNamespace-from unittest.mock import MagicMock, patch+from unittest.mock import Mockimport pytestfrom flask import Flask-from sqlalchemy import Engine, event-from sqlalchemy.orm import Session, scoped_session, sessionmaker-from werkzeug.datastructures import FileStorage+from flask_restx import Resourcefrom werkzeug.exceptions import NotFound-import servicesfrom controllers.common.errors import (FilenameNotExistsError,FileTooLargeError,@@ -24,690 +22,234 @@ from controllers.common.errors import ()from controllers.console import console_nsfrom controllers.console.error import AccountNotLinkTenantError+from controllers.console.workspace import workspace as controllerfrom controllers.console.workspace.error import CurrentWorkspaceArchivedError-from controllers.console.workspace.workspace import (- CurrentWorkspaceSummaryApi,- CustomConfigWorkspaceApi,- SwitchWorkspaceApi,- TenantInfoResponse,- TenantListApi,- WebappLogoWorkspaceApi,- WorkspaceInfoApi,- WorkspaceListApi,- WorkspaceLogoUploadResponse,- WorkspacePermissionApi,- WorkspacePermissionResponse,-)-from enums import CloudPlan, DeploymentEdition-from extensions.storage.storage_type import StorageType-from libs.datetime_utils import naive_utc_now+from enums import CloudPlanfrom machinery.context import RequestContext-from models.account import Account, Tenant, TenantAccountJoin, TenantCustomConfigDict, TenantStatus-from models.enums import CreatorUserRole-from models.model import UploadFile-from repositories.workspace_query_repository import WorkspaceQueryRepository-from services import workspace_plan_gateway-from services.workspace_query_service import WorkspaceQueryService, WorkspaceRecord-from tests.unit_tests.config_override import config_overrides_context+from services.errors import file as file_errors+from services.errors.workspace import WorkspaceArchivedError, WorkspaceNotFoundError, WorkspaceNotLinkedError+from services.workspace.contracts import (+ WorkspaceCustomConfig,+ WorkspaceCustomConfigChanges,+ WorkspacePage,+ WorkspacePermission,+ WorkspaceSnapshot,+ WorkspaceSummary,+)+from services.workspace.provisioning_service import WorkspaceProvisioningService+from services.workspace.service import WorkspaceQueryService, WorkspaceService+CONTEXT = RequestContext("request-1", "trace-1", "account-1", "workspace-1")+NOW = datetime(2026, 1, 1)-def workspace_session(sqlite_engine: Engine) -> Iterator[scoped_session[Session]]:- """Provide the callable scoped session expected by Flask-SQLAlchemy controllers."""- Tenant.metadata.create_all(sqlite_engine, tables=[Tenant.__table__, TenantAccountJoin.__table__])- session = scoped_session(sessionmaker(bind=sqlite_engine, expire_on_commit=False))- try:- yield session- finally:- session.remove()++@dataclass+class WorkspaceMocks:+ management: Mock+ queries: Mock+ provisioning: Mock+++@dataclass+class Services:+ workspaces: WorkspaceMocks@pytest.fixture-def workspace_plan_dependencies(monkeypatch: pytest.MonkeyPatch) -> tuple[MagicMock, MagicMock]:- get_plan_bulk = MagicMock()- get_features = MagicMock()- monkeypatch.setattr(workspace_plan_gateway.BillingService, "get_plan_bulk", get_plan_bulk)- monkeypatch.setattr(workspace_plan_gateway.FeatureService, "get_features", get_features)- return get_plan_bulk, get_features---def configure_workspace_plans(- monkeypatch: pytest.MonkeyPatch,- *,- edition: DeploymentEdition = DeploymentEdition.CLOUD,-) -> None:- monkeypatch.setattr(- workspace_plan_gateway,- "dify_config",- SimpleNamespace(- DEPLOYMENT_EDITION=edition,- ),+def workspaces(monkeypatch: pytest.MonkeyPatch) -> WorkspaceMocks:+ services = WorkspaceMocks(+ management=Mock(spec=WorkspaceService),+ queries=Mock(spec=WorkspaceQueryService),+ provisioning=Mock(spec=WorkspaceProvisioningService),)+ monkeypatch.setattr(controller, "application_services", lambda: Services(services))+ return services-def features_with_plan(plan: str) -> SimpleNamespace:- return SimpleNamespace(billing=SimpleNamespace(subscription=SimpleNamespace(plan=plan)))---def make_account(account_id: str = "u1") -> Account:- account = Account(name="Test User", email=f"{account_id}@example.com")- account.id = account_id- return account---def make_tenant(- tenant_id: str = "t1",- *,- name: str | None = None,- status: TenantStatus = TenantStatus.NORMAL,- custom_config: TenantCustomConfigDict | None = None,-) -> Tenant:- tenant = Tenant(name=name or f"Tenant {tenant_id}", status=status)- tenant.id = tenant_id- tenant.created_at = naive_utc_now()- if custom_config is not None:- tenant.custom_config_dict = custom_config- return tenant---def make_account_with_tenant(tenant: Tenant) -> Account:- account = make_account()- account._current_tenant = tenant- return account---class TestTenantListApi:- def test_get_passes_context_and_serializes_workspaces(self):- api = TenantListApi()- method = unwrap(api.get)- request_context = RequestContext(- request_id="request-1",- trace_id="trace-1",- account_id="account-1",- active_workspace_id="workspace-1",- )- created_at = naive_utc_now()- last_opened_at = naive_utc_now()- workspaces = MagicMock()- workspaces.list_for_account.return_value = (- WorkspaceRecord(- id="workspace-1",- name="Workspace 1",- status=TenantStatus.NORMAL.value,- created_at=created_at,- last_opened_at=last_opened_at,- ),- WorkspaceRecord(- id="workspace-2",- name=None,- status=TenantStatus.NORMAL.value,- created_at=created_at,- last_opened_at=None,- ),- )- plans = MagicMock()- plans.resolve_many.return_value = {"workspace-1": CloudPlan.TEAM}- workspace_queries = WorkspaceQueryService(workspaces=workspaces, plans=plans)- application_services_mock = SimpleNamespace(workspace_queries=workspace_queries)-- with patch(- "controllers.console.workspace.workspace.application_services", return_value=application_services_mock- ):- result, status = method(api, request_context=request_context)-- assert status == HTTPStatus.OK- assert result == {- "workspaces": [- {- "id": "workspace-1",- "name": "Workspace 1",- "plan": "team",- "status": "normal",- "created_at": int(created_at.timestamp()),- "last_opened_at": int(last_opened_at.timestamp()),- "current": True,- },- {- "id": "workspace-2",- "name": None,- "plan": "sandbox",- "status": "normal",- "created_at": int(created_at.timestamp()),- "last_opened_at": None,- "current": False,- },- ]+def test_workspace_list_serialization(workspaces: WorkspaceMocks) -> None:+ workspaces.queries.list_for_account.return_value = (+ WorkspaceSummary("workspace-1", "Test", "team", "normal", NOW, None, True),+ )+ body, status = unwrap(controller.TenantListApi.get)(controller.TenantListApi(), CONTEXT)+ assert status == HTTPStatus.OK+ assert body["workspaces"] == [+ {+ "id": "workspace-1",+ "name": "Test",+ "plan": "team",+ "status": "normal",+ "created_at": int(NOW.timestamp()),+ "last_opened_at": None,+ "current": True,}- workspaces.list_for_account.assert_called_once_with("account-1")- plans.resolve_many.assert_called_once_with(["workspace-1", "workspace-2"])---class TestWorkspaceQueryRepository:- def test_list_for_account_filters_orders_and_maps(self, workspace_session: scoped_session[Session]):- now = naive_utc_now()- earlier = make_tenant("workspace-1")- earlier.created_at = now - timedelta(days=1)- later = make_tenant("workspace-2")- later.created_at = now- archived = make_tenant("workspace-3", status=TenantStatus.ARCHIVE)- other_account = make_tenant("workspace-4")- last_opened_at = now - timedelta(hours=1)- workspace_session.add_all(- [- earlier,- later,- archived,- other_account,- TenantAccountJoin(- tenant_id=earlier.id,- account_id="account-1",- current=True,- last_opened_at=last_opened_at,- ),- TenantAccountJoin(tenant_id=later.id, account_id="account-1"),- TenantAccountJoin(tenant_id=archived.id, account_id="account-1"),- TenantAccountJoin(tenant_id=archived.id, account_id="account-3"),- TenantAccountJoin(tenant_id=other_account.id, account_id="account-2"),- ]- )- workspace_session.commit()-- repository = WorkspaceQueryRepository(workspace_session.session_factory)- result = repository.list_for_account("account-1")- membership_ids = repository.list_ids_for_account("account-1")- access_workspaces = repository.list_account_access_workspaces("account-1")-- assert repository.has_active_for_account("account-1") is True- assert repository.has_active_for_account("missing-account") is False- assert result == (- WorkspaceRecord(- id=earlier.id,- name=earlier.name,- status=TenantStatus.NORMAL.value,- created_at=earlier.created_at,- last_opened_at=last_opened_at,- ),- WorkspaceRecord(- id=later.id,- name=later.name,- status=TenantStatus.NORMAL.value,- created_at=later.created_at,- last_opened_at=None,- ),- )- assert set(membership_ids) == {earlier.id, later.id, archived.id}- access_by_id = {workspace.id: workspace for workspace in access_workspaces}- assert set(access_by_id) == {earlier.id, later.id, archived.id}- assert access_by_id[earlier.id].current is True- assert access_by_id[earlier.id].role == "normal"- assert repository.has_active_membership("account-1") is True- assert repository.has_active_membership("account-3") is False---class TestDeploymentWorkspacePlanGateway:- def test_saas_uses_bulk_plans_and_feature_fallback(- self,- monkeypatch: pytest.MonkeyPatch,- workspace_plan_dependencies: tuple[MagicMock, MagicMock],- ) -> None:- configure_workspace_plans(monkeypatch)- get_plan_bulk, get_features = workspace_plan_dependencies- get_plan_bulk.return_value = {"workspace-1": {"plan": CloudPlan.TEAM, "expiration_date": 0}}- get_features.return_value = features_with_plan(CloudPlan.PROFESSIONAL)-- result = workspace_plan_gateway.DeploymentWorkspacePlanGateway().resolve_many(["workspace-1", "workspace-2"])-- assert result == {"workspace-1": CloudPlan.TEAM, "workspace-2": CloudPlan.PROFESSIONAL}- get_plan_bulk.assert_called_once()- assert list(get_plan_bulk.call_args.args[0]) == ["workspace-1", "workspace-2"]- get_features.assert_called_once_with("workspace-2", exclude_vector_space=True)-- def test_saas_empty_bulk_result_falls_back_to_features(- self,- monkeypatch: pytest.MonkeyPatch,- workspace_plan_dependencies: tuple[MagicMock, MagicMock],- caplog: pytest.LogCaptureFixture,- ) -> None:- configure_workspace_plans(monkeypatch)- get_plan_bulk, get_features = workspace_plan_dependencies- get_plan_bulk.return_value = {}- get_features.return_value = features_with_plan(CloudPlan.TEAM)-- with caplog.at_level(logging.WARNING, logger=workspace_plan_gateway.__name__):- result = workspace_plan_gateway.DeploymentWorkspacePlanGateway().resolve_many(- ["workspace-1", "workspace-2"]- )-- assert result == {"workspace-1": CloudPlan.TEAM, "workspace-2": CloudPlan.TEAM}- assert "get_plan_bulk returned empty result, falling back to FeatureService" in caplog.messages-- def test_non_saas_uses_features(- self,- monkeypatch: pytest.MonkeyPatch,- workspace_plan_dependencies: tuple[MagicMock, MagicMock],- ) -> None:- configure_workspace_plans(- monkeypatch,- edition=DeploymentEdition.COMMUNITY,- )- get_plan_bulk, get_features = workspace_plan_dependencies- get_features.return_value = features_with_plan(CloudPlan.SANDBOX)-- result = workspace_plan_gateway.DeploymentWorkspacePlanGateway().resolve_many(["workspace-1"])-- assert result == {"workspace-1": CloudPlan.SANDBOX}- get_plan_bulk.assert_not_called()- get_features.assert_called_once_with("workspace-1", exclude_vector_space=True)-- def test_enterprise_only_skips_external_lookups(- self,- monkeypatch: pytest.MonkeyPatch,- workspace_plan_dependencies: tuple[MagicMock, MagicMock],- ) -> None:- configure_workspace_plans(- monkeypatch,- edition=DeploymentEdition.ENTERPRISE,- )- get_plan_bulk, get_features = workspace_plan_dependencies-- result = workspace_plan_gateway.DeploymentWorkspacePlanGateway().resolve_many(["workspace-1", "workspace-2"])-- assert result == {"workspace-1": CloudPlan.SANDBOX, "workspace-2": CloudPlan.SANDBOX}- get_plan_bulk.assert_not_called()- get_features.assert_not_called()---class TestWorkspaceListApi:- def test_get_success(self, app: Flask, sqlite_session: Session):- api = WorkspaceListApi()- method = unwrap(api.get)- tenant = make_tenant("t1", name="T")- paginate_result = MagicMock(items=[tenant], has_next=False, total=1)- with (- app.test_request_context("/all-workspaces", query_string={"page": 1, "limit": 20}),- patch("controllers.console.workspace.workspace.paginate_query", return_value=paginate_result),- ):- result, status = method(api, sqlite_session)- assert status == HTTPStatus.OK- assert result["total"] == 1- assert result["has_more"] is False-- def test_get_has_next_true(self, app: Flask, sqlite_session: Session):- api = WorkspaceListApi()- method = unwrap(api.get)- tenant = make_tenant("t1", name="T")- paginate_result = MagicMock(items=[tenant], has_next=True, total=10)- with (- app.test_request_context("/all-workspaces", query_string={"page": 1, "limit": 1}),- patch("controllers.console.workspace.workspace.paginate_query", return_value=paginate_result),- ):- result, status = method(api, sqlite_session)- assert status == HTTPStatus.OK- assert result["has_more"] is True---def test_legacy_current_workspace_routes_are_not_registered():- urls = {url for _resource, resource_urls, _route_doc, _kwargs in console_ns.resources for url in resource_urls}+ ]+ workspaces.queries.list_for_account.assert_called_once_with(CONTEXT)- assert "/workspaces/current" not in urls- assert "/info" not in urls---class TestCurrentWorkspaceSummaryApi:- def test_get_summary(self, app: Flask, sqlite_session: Session):- api = CurrentWorkspaceSummaryApi()- method = unwrap(api.get)- tenant = make_tenant()- user = make_account_with_tenant(tenant)- session = sqlite_session- summary = {- "id": tenant.id,- "name": tenant.name,- "role": "owner",- "plan": CloudPlan.SANDBOX,- "credits": 180,- }- with (- app.test_request_context("/workspaces/current/summary"),- patch(- "controllers.console.workspace.workspace.WorkspaceService.get_current_workspace_summary",- return_value=summary,- ) as get_summary,- ):- result, status = method(api, session, user)-- assert status == HTTPStatus.OK- assert result == {- "id": tenant.id,- "name": tenant.name,- "role": "owner",- "plan": "sandbox",- "credits": 180,- }- get_summary.assert_called_once_with(tenant, user.id, session=session)-- def test_get_archived_tenant_returns_conflict(self, app: Flask, sqlite_session: Session):- api = CurrentWorkspaceSummaryApi()- method = unwrap(api.get)- tenant = make_tenant(status=TenantStatus.ARCHIVE)- user = make_account_with_tenant(tenant)-- with app.test_request_context("/workspaces/current/summary"):- with pytest.raises(CurrentWorkspaceArchivedError) as exc_info:- method(api, sqlite_session, user)-- assert exc_info.value.code == HTTPStatus.CONFLICT- assert exc_info.value.error_code == "current_workspace_archived"---class TestTenantInfoResponse:- def test_tenant_info_response_normalizes_enum_and_datetime(self):- created_at = naive_utc_now()- payload = TenantInfoResponse.model_validate(- {"id": "t1", "status": TenantStatus.NORMAL, "plan": CloudPlan.TEAM, "created_at": created_at}- ).model_dump(mode="json")- assert payload["status"] == "normal"- assert payload["plan"] == "team"- assert payload["created_at"] == int(created_at.timestamp())-- def test_tenant_info_response_has_typed_custom_config(self):- payload = TenantInfoResponse.model_validate(- {- "id": "t1",- "custom_config": {- "remove_webapp_brand": True,- "replace_webapp_logo": "logo-file-id",- "ignored": "value",- },- }- ).model_dump(mode="json")- assert payload["custom_config"] == {"remove_webapp_brand": True, "replace_webapp_logo": "logo-file-id"}---class TestSwitchWorkspaceApi:- def test_switch_success(self, app: Flask, workspace_session: scoped_session[Session]):- api = SwitchWorkspaceApi()- method = unwrap(api.post)- payload = {"tenant_id": "t2"}- tenant = make_tenant("t2")- workspace_session.add(tenant)- workspace_session.commit()- user = make_account()- with (- app.test_request_context("/workspaces/switch", json=payload),- patch("controllers.console.workspace.workspace.TenantService.switch_tenant") as switch_tenant,- patch(- "controllers.console.workspace.workspace.WorkspaceService.get_tenant_info", return_value={"id": "t2"}- ),- ):- result = method(api, workspace_session, user)-- assert result["result"] == "success"- switch_tenant.assert_called_once_with(user, "t2", session=workspace_session)-- def test_switch_not_linked(self, app: Flask, sqlite_session: Session):- api = SwitchWorkspaceApi()- method = unwrap(api.post)- payload = {"tenant_id": "bad"}- user = make_account()- with (- app.test_request_context("/workspaces/switch", json=payload),- patch("controllers.console.workspace.workspace.TenantService.switch_tenant", side_effect=Exception),- ):- with pytest.raises(AccountNotLinkTenantError):- method(api, sqlite_session, user)-- def test_switch_tenant_not_found(self, app: Flask, workspace_session: scoped_session[Session]):- api = SwitchWorkspaceApi()- method = unwrap(api.post)- payload = {"tenant_id": "missing"}- user = make_account()- with (- app.test_request_context("/workspaces/switch", json=payload),- patch("controllers.console.workspace.workspace.TenantService.switch_tenant"),- ):- with pytest.raises(ValueError):- method(api, workspace_session, user)---class TestCustomConfigWorkspaceApi:- def test_get_workspace_not_found(self, app: Flask, workspace_session: scoped_session[Session]):- api = CustomConfigWorkspaceApi()- method = unwrap(api.get)-- with app.test_request_context("/workspaces/custom-config"), pytest.raises(NotFound):- method(api, workspace_session, "missing")-- def test_get_defaults(self, app: Flask, workspace_session: scoped_session[Session]):- api = CustomConfigWorkspaceApi()- method = unwrap(api.get)- tenant = make_tenant(custom_config={})- workspace_session.add(tenant)- workspace_session.commit()-- with app.test_request_context("/workspaces/custom-config"):- result = method(api, workspace_session, tenant.id)-- assert result == {"remove_webapp_brand": False, "replace_webapp_logo": None}-- def test_get_configured_brand(self, app: Flask, workspace_session: scoped_session[Session]):- api = CustomConfigWorkspaceApi()- method = unwrap(api.get)- tenant = make_tenant(custom_config={"remove_webapp_brand": True, "replace_webapp_logo": "logo-file-id"})- workspace_session.add(tenant)- workspace_session.commit()-- with (- app.test_request_context("/workspaces/custom-config"),- config_overrides_context(FILES_URL="https://files.example.com"),- ):- result = method(api, workspace_session, tenant.id)-- assert result == {- "remove_webapp_brand": True,- "replace_webapp_logo": f"https://files.example.com/files/workspaces/{tenant.id}/webapp-logo",- }+def test_admin_pagination(app: Flask, workspaces: WorkspaceMocks) -> None:+ workspaces.management.list_all.return_value = WorkspacePage(+ (WorkspaceSnapshot("w1", "Test", "archive", NOW),), 5, 2, 2, True+ )+ with app.test_request_context("/all-workspaces?page=2&limit=2"):+ body, status = unwrap(controller.WorkspaceListApi.get)(controller.WorkspaceListApi())+ assert status == 200+ assert body == {+ "data": [{"id": "w1", "name": "Test", "status": "archive", "created_at": int(NOW.timestamp())}],+ "total": 5,+ "page": 2,+ "limit": 2,+ "has_more": True,+ }+ workspaces.management.list_all.assert_called_once_with(page=2, limit=2)+++def test_summary(workspaces: WorkspaceMocks) -> None:+ workspaces.management.current_summary.return_value = {+ "id": "w1",+ "name": "Test",+ "role": "owner",+ "plan": CloudPlan.TEAM,+ "credits": -1,+ }+ body, status = unwrap(controller.CurrentWorkspaceSummaryApi.get)(controller.CurrentWorkspaceSummaryApi(), CONTEXT)+ assert status == 200+ assert body["credits"] == -1+ workspaces.management.current_summary.assert_called_once_with(CONTEXT)+++ ("error", "http_error"),+ [(WorkspaceArchivedError(), CurrentWorkspaceArchivedError), (WorkspaceNotFoundError(), NotFound)],+)+def test_summary_errors(workspaces: WorkspaceMocks, error: Exception, http_error: type[Exception]) -> None:+ workspaces.management.current_summary.side_effect = error+ with pytest.raises(http_error):+ unwrap(controller.CurrentWorkspaceSummaryApi.get)(controller.CurrentWorkspaceSummaryApi(), CONTEXT)+++def test_switch_and_rename(app: Flask, workspaces: WorkspaceMocks) -> None:+ workspaces.management.switch.return_value = {"id": "target", "name": "Switched"}+ workspaces.management.rename.return_value = {"id": "workspace-1", "name": "Renamed"}+ with app.test_request_context(json={"tenant_id": "target"}):+ body = unwrap(controller.SwitchWorkspaceApi.post)(controller.SwitchWorkspaceApi(), CONTEXT)+ assert body["new_tenant"]["id"] == "target"+ workspaces.management.switch.assert_called_once_with(CONTEXT, "target")+ with app.test_request_context(json={"name": "Renamed"}):+ body = unwrap(controller.WorkspaceInfoApi.post)(controller.WorkspaceInfoApi(), CONTEXT)+ assert body["tenant"]["name"] == "Renamed"+ workspaces.management.rename.assert_called_once_with(CONTEXT, "Renamed")+++def test_switch_not_linked(app: Flask, workspaces: WorkspaceMocks) -> None:+ workspaces.management.switch.side_effect = WorkspaceNotLinkedError()+ with app.test_request_context(json={"tenant_id": "target"}), pytest.raises(AccountNotLinkTenantError):+ unwrap(controller.SwitchWorkspaceApi.post)(controller.SwitchWorkspaceApi(), CONTEXT)+++def test_config_response_and_partial_update(app: Flask, workspaces: WorkspaceMocks) -> None:+ workspaces.management.custom_config.return_value = WorkspaceCustomConfig(True, "https://files/logo")+ assert unwrap(controller.CustomConfigWorkspaceApi.get)(controller.CustomConfigWorkspaceApi(), CONTEXT) == {+ "remove_webapp_brand": True,+ "replace_webapp_logo": "https://files/logo",+ }+ workspaces.management.update_custom_config.return_value = {"id": "workspace-1"}+ with app.test_request_context(json={"remove_webapp_brand": False}):+ body = unwrap(controller.CustomConfigWorkspaceApi.post)(controller.CustomConfigWorkspaceApi(), CONTEXT)+ assert body["result"] == "success"+ workspaces.management.update_custom_config.assert_called_once_with(+ CONTEXT, WorkspaceCustomConfigChanges(False, None)+ )+- def test_post_success(self, app: Flask, workspace_session: scoped_session[Session]):- api = CustomConfigWorkspaceApi()- method = unwrap(api.post)- tenant = make_tenant(custom_config={})- workspace_session.add(tenant)- workspace_session.commit()-- payload = {"remove_webapp_brand": True}- events = []- event.listen(workspace_session, "after_commit", lambda _: events.append("commit"))- with (- app.test_request_context("/workspaces/custom-config", json=payload),- patch(- "controllers.console.workspace.workspace.WorkspaceService.get_tenant_info",- side_effect=lambda *args, **kwargs: events.append("get_tenant_info") or {"id": "t1"},- ),- ):- result = method(api, workspace_session, "t1")- assert result["result"] == "success"- assert events == ["commit", "get_tenant_info"]-- def test_logo_fallback(self, app: Flask, workspace_session: scoped_session[Session]):- api = CustomConfigWorkspaceApi()- method = unwrap(api.post)-- tenant = make_tenant(custom_config={"replace_webapp_logo": "old-logo"})- workspace_session.add(tenant)- workspace_session.commit()-- payload = {"remove_webapp_brand": False}-- with (- app.test_request_context("/workspaces/custom-config", json=payload),- patch(- "controllers.console.workspace.workspace.WorkspaceService.get_tenant_info",- return_value={"id": "t1"},- ),- ):- result = method(api, workspace_session, "t1")-- assert tenant.custom_config_dict["replace_webapp_logo"] == "old-logo"- assert result["result"] == "success"---class TestWebappLogoWorkspaceApi:- def test_no_file(self, app: Flask):- api = WebappLogoWorkspaceApi()- method = unwrap(api.post)- user = make_account()- with app.test_request_context("/upload", data={}):- with pytest.raises(NoFileUploadedError):- method(api, user)-- def test_too_many_files(self, app: Flask):- api = WebappLogoWorkspaceApi()- method = unwrap(api.post)- data = {"file": MagicMock(), "extra": MagicMock()}- user = make_account()- with app.test_request_context("/upload", data=data):- with pytest.raises(TooManyFilesError):- method(api, user)-- def test_invalid_extension(self, app: Flask):- api = WebappLogoWorkspaceApi()- method = unwrap(api.post)- file = MagicMock(filename="test.txt")- user = make_account()- with app.test_request_context("/upload", data={"file": file}):- with pytest.raises(UnsupportedFileTypeError):- method(api, user)-- def test_upload_success(self, app: Flask):- api = WebappLogoWorkspaceApi()- method = unwrap(api.post)- file = FileStorage(stream=BytesIO(b"data"), filename="logo.png", content_type="image/png")- user = make_account()- upload = UploadFile(- tenant_id="t1",- storage_type=StorageType.LOCAL,- key="logo.png",- name="logo.png",- size=4,- extension="png",- mime_type="image/png",- created_by_role=CreatorUserRole.ACCOUNT,- created_by=user.id,- created_at=naive_utc_now(),- used=False,- )- upload.id = "file1"- with (- app.test_request_context("/upload", data={"file": file}, content_type="multipart/form-data"),- patch("controllers.console.workspace.workspace.FileService") as fs,- patch("controllers.console.workspace.workspace.db") as mock_db,- ):- mock_db.engine = MagicMock()- fs.return_value.upload_file.return_value = upload- result, status = method(api, user)- assert status == HTTPStatus.CREATED- assert result == {"id": "file1"}- assert WorkspaceLogoUploadResponse.model_validate(result).model_dump(mode="json") == {"id": "file1"}-- def test_filename_missing(self, app: Flask):- api = WebappLogoWorkspaceApi()- method = unwrap(api.post)- file = FileStorage(stream=BytesIO(b"data"), filename="", content_type="image/png")- user = make_account()- with app.test_request_context("/upload", data={"file": file}, content_type="multipart/form-data"):- with pytest.raises(FilenameNotExistsError):- method(api, user)-- def test_file_too_large(self, app: Flask):- api = WebappLogoWorkspaceApi()- method = unwrap(api.post)- file = FileStorage(stream=BytesIO(b"x"), filename="logo.png", content_type="image/png")- user = make_account()- with (- app.test_request_context("/upload", data={"file": file}, content_type="multipart/form-data"),- patch("controllers.console.workspace.workspace.FileService") as fs,- patch("controllers.console.workspace.workspace.db") as mock_db,- ):- mock_db.engine = MagicMock()- fs.return_value.upload_file.side_effect = services.errors.file.FileTooLargeError("too big")- with pytest.raises(FileTooLargeError):- method(api, user)-- def test_service_unsupported_file(self, app: Flask):- api = WebappLogoWorkspaceApi()- method = unwrap(api.post)- file = FileStorage(stream=BytesIO(b"x"), filename="logo.png", content_type="image/png")- user = make_account()- with (- app.test_request_context("/upload", data={"file": file}, content_type="multipart/form-data"),- patch("controllers.console.workspace.workspace.FileService") as fs,- patch("controllers.console.workspace.workspace.db") as mock_db,- ):- mock_db.engine = MagicMock()- fs.return_value.upload_file.side_effect = services.errors.file.UnsupportedFileTypeError()- with pytest.raises(UnsupportedFileTypeError):- method(api, user)---class TestWorkspaceInfoApi:- def test_post_success(self, app: Flask, workspace_session: scoped_session[Session]):- api = WorkspaceInfoApi()- method = unwrap(api.post)- tenant = make_tenant()- workspace_session.add(tenant)- workspace_session.commit()-- payload = {"name": "New Name"}- events = []- with (- app.test_request_context("/workspaces/info", json=payload),- patch("controllers.console.workspace.workspace.db.get_or_404", return_value=tenant),- patch("controllers.console.workspace.workspace.db.session", workspace_session),- patch(- "controllers.console.workspace.workspace.WorkspaceService.get_tenant_info",- side_effect=lambda *args, **kwargs: (- events.append("get_tenant_info") or {"id": "t1", "name": "New Name"}- ),- ),- ):- session = workspace_session()- event.listen(session, "after_commit", lambda _session: events.append("commit"))- result = method(api, session, "t1")- assert result["result"] == "success"- assert events == ["commit", "get_tenant_info"]-- def test_no_current_tenant(self, app: Flask, sqlite_session: Session):- api = WorkspaceInfoApi()- method = unwrap(api.post)- payload = {"name": "X"}- with app.test_request_context("/workspaces/info", json=payload):- with pytest.raises(ValueError):- method(api, sqlite_session, None)---class TestWorkspacePermissionApi:- def test_get_success(self, app: Flask):- api = WorkspacePermissionApi()- method = unwrap(api.get)- permission = MagicMock(workspace_id="t1", allow_member_invite=True, allow_owner_transfer=False)- with (- app.test_request_context("/permission"),- patch(- "controllers.console.workspace.workspace.EnterpriseService.WorkspacePermissionService.get_permission",- return_value=permission,- ),- ):- result, status = method(api, "t1")- assert status == HTTPStatus.OK- expected = {"workspace_id": "t1", "allow_member_invite": True, "allow_owner_transfer": False}- assert result == expected- assert WorkspacePermissionResponse.model_validate(result).model_dump(mode="json") == expected-- def test_no_current_tenant(self, app: Flask):- api = WorkspacePermissionApi()- method = unwrap(api.get)- with app.test_request_context("/permission"):- with pytest.raises(ValueError):- method(api, None)+ ("resource", "method", "payload", "service_method"),+ [+ pytest.param(+ controller.CustomConfigWorkspaceApi,+ controller.CustomConfigWorkspaceApi.get,+ {},+ lambda management: management.custom_config,+ id="custom_config",+ ),+ pytest.param(+ controller.CustomConfigWorkspaceApi,+ controller.CustomConfigWorkspaceApi.post,+ {},+ lambda management: management.update_custom_config,+ id="update_custom_config",+ ),+ pytest.param(+ controller.WorkspaceInfoApi,+ controller.WorkspaceInfoApi.post,+ {"name": "New"},+ lambda management: management.rename,+ id="rename",+ ),+ ],+)+def test_missing_workspace(+ app: Flask,+ workspaces: WorkspaceMocks,+ resource: type[Resource],+ method: Callable[..., object],+ payload: dict[str, object],+ service_method: Callable[[Mock], Mock],+) -> None:+ service_method(workspaces.management).side_effect = WorkspaceNotFoundError()+ with app.test_request_context(json=payload), pytest.raises(NotFound):+ unwrap(method)(resource(), CONTEXT)+++ ("files", "error"),+ [+ ({}, NoFileUploadedError),+ ({"file": (BytesIO(b"x"), "a.png"), "extra": (BytesIO(b"x"), "b.png")}, TooManyFilesError),+ ({"file": (BytesIO(b"x"), "")}, FilenameNotExistsError),+ ],+)+def test_upload_form_errors(+ app: Flask, workspaces: WorkspaceMocks, files: dict[str, tuple[BytesIO, str]], error: type[Exception]+) -> None:+ with app.test_request_context(method="POST", data=files), pytest.raises(error):+ unwrap(controller.WebappLogoWorkspaceApi.post)(controller.WebappLogoWorkspaceApi(), CONTEXT)+ workspaces.management.upload_logo.assert_not_called()+++def test_upload(app: Flask, workspaces: WorkspaceMocks) -> None:+ workspaces.management.upload_logo.return_value = "upload-1"+ with app.test_request_context(method="POST", data={"file": (BytesIO(b"image"), "logo.PNG")}):+ result = unwrap(controller.WebappLogoWorkspaceApi.post)(controller.WebappLogoWorkspaceApi(), CONTEXT)+ assert result == ({"id": "upload-1"}, HTTPStatus.CREATED)+ workspaces.management.upload_logo.assert_called_once_with(+ CONTEXT, filename="logo.PNG", content=b"image", mimetype="image/png"+ )+++ ("error", "http_error"),+ [+ (file_errors.FileTooLargeError(), FileTooLargeError),+ (file_errors.UnsupportedFileTypeError(), UnsupportedFileTypeError),+ ],+)+def test_upload_service_errors(+ app: Flask, workspaces: WorkspaceMocks, error: Exception, http_error: type[Exception]+) -> None:+ workspaces.management.upload_logo.side_effect = error+ with app.test_request_context(method="POST", data={"file": (BytesIO(b"x"), "logo.png")}), pytest.raises(http_error):+ unwrap(controller.WebappLogoWorkspaceApi.post)(controller.WebappLogoWorkspaceApi(), CONTEXT)+++def test_permissions(workspaces: WorkspaceMocks) -> None:+ workspaces.management.permission.return_value = WorkspacePermission("workspace-1", True, False)+ body, status = unwrap(controller.WorkspacePermissionApi.get)(controller.WorkspacePermissionApi(), CONTEXT)+ assert status == 200+ assert body == {"workspace_id": "workspace-1", "allow_member_invite": True, "allow_owner_transfer": False}+ workspaces.management.permission.assert_called_once_with(CONTEXT)+++def test_removed_current_workspace_routes_stay_unregistered() -> None:+ urls = {url for resource in console_ns.resources for url in resource.urls}+ assert "/workspaces/current" not in urls+ assert "/workspaces/current/tool-provider" not in urlsdiff --git a/api/tests/unit_tests/controllers/inner_api/test_agent_files.py b/api/tests/unit_tests/controllers/inner_api/test_agent_files.pyindex 040a0f13abc..efda15a4ef5 100644--- a/api/tests/unit_tests/controllers/inner_api/test_agent_files.py+++ b/api/tests/unit_tests/controllers/inner_api/test_agent_files.py@@ -44,15 +44,17 @@ def test_upload_request_returns_origin_free_uri(app: Flask, unbound_session: Sessession = unbound_sessionwith app.test_request_context("/", method="POST", json=payload):with (- patch(f"{MODULE}.TenantService") as tenant_service,+ patch(f"{MODULE}.application_services") as service_provider,patch(f"{MODULE}.get_user", return_value=user),patch(f"{MODULE}.get_signed_file_uri_for_plugin", return_value="/files/upload/for-plugin?sign=1") as sign,):- tenant_service.get_tenant_by_id.return_value = tenant+ tenant_service = service_provider.return_value.workspaces.management+ service_provider.return_value.workspaces.members = tenant_service+ tenant_service.get.return_value = tenantresponse = _raw(AgentFileUploadRequestApi.post)(AgentFileUploadRequestApi(), session)assert response == {"upload_uri": "/files/upload/for-plugin?sign=1"}- tenant_service.get_tenant_by_id.assert_called_once_with("tenant-1", session=session)+ tenant_service.get.assert_called_once_with("tenant-1")sign.assert_called_once_with(filename="report.pdf",mimetype="application/pdf",@@ -93,10 +95,12 @@ def test_download_request_returns_origin_free_uri_for_sandbox(app: Flask, unbounsession = unbound_sessionwith app.test_request_context("/", method="POST", json=payload):with (- patch(f"{MODULE}.TenantService") as tenant_service,+ patch(f"{MODULE}.application_services") as service_provider,patch(f"{MODULE}.FileRequestService") as service,):- tenant_service.get_tenant_by_id.return_value = _tenant()+ tenant_service = service_provider.return_value.workspaces.management+ service_provider.return_value.workspaces.members = tenant_service+ tenant_service.get.return_value = _tenant()service.return_value.request_download.return_value = DownloadFileRequestResult(filename="report.pdf",mime_type="application/pdf",@@ -136,10 +140,12 @@ def test_download_request_binds_frontend_url(session = unbound_sessionwith app.test_request_context("/", method="POST", json=payload):with (- patch(f"{MODULE}.TenantService") as tenant_service,+ patch(f"{MODULE}.application_services") as service_provider,patch(f"{MODULE}.FileRequestService") as service,):- tenant_service.get_tenant_by_id.return_value = _tenant()+ tenant_service = service_provider.return_value.workspaces.management+ service_provider.return_value.workspaces.members = tenant_service+ tenant_service.get.return_value = _tenant()service.return_value.request_download.return_value = DownloadFileRequestResult(filename="report.pdf",mime_type="application/pdf",diff --git a/api/tests/unit_tests/controllers/inner_api/workspace/test_workspace.py b/api/tests/unit_tests/controllers/inner_api/workspace/test_workspace.pyindex f7c8e653a49..14c884182ee 100644--- a/api/tests/unit_tests/controllers/inner_api/workspace/test_workspace.py+++ b/api/tests/unit_tests/controllers/inner_api/workspace/test_workspace.py@@ -1,367 +1,180 @@-"""-Unit tests for inner_api workspace module+"""Internal workspace transport behavior and admission."""-Tests Pydantic model validation and endpoint handler logic.-Auth/setup decorators are tested separately in test_auth_wraps.py;-handler tests use inspect.unwrap() to bypass them and focus on business logic.-"""--import inspect+from collections.abc import Callable+from dataclasses import dataclassfrom datetime import datetime-from unittest.mock import patch+from inspect import unwrap+from unittest.mock import Mockimport pytestfrom flask import Flask-from flask_restx import Resource-from pydantic import ValidationError-from sqlalchemy.orm import Session, scoped_session, sessionmaker+from flask.typing import ResponseReturnValue+from flask_restx import Api, Resourcefrom werkzeug.exceptions import UnprocessableEntity-from controllers.inner_api.workspace.workspace import (- EnterpriseWorkspace,- EnterpriseWorkspaceMember,- EnterpriseWorkspaceNoOwnerEmail,- WorkspaceCreatePayload,- WorkspaceMemberPayload,- WorkspaceOwnerlessPayload,-)-from models import Account, Tenant-from models.account import TenantAccountJoin, TenantAccountRole, TenantStatus-from services.account_service import (- EnterpriseWorkspaceMemberAccountNotFoundError,- EnterpriseWorkspaceMemberWorkspaceNotFoundError,+from controllers.inner_api.workspace import workspace as controller+from controllers.inner_api.wraps import InnerApiUnauthorizedError+from extensions.application_services.workspace import WorkspaceServices+from libs.external_api import register_external_error_handlers+from services.account_errors import AccountNotFoundError+from services.errors.workspace import (+ InvalidWorkspaceMemberRoleError,+ WorkspaceNotFoundError,+ WorkspaceOwnerNotFoundError,+ WorkspacesLimitExceededError,)-from tests.unit_tests.config_override import config_overrides_context---def database_session(sqlite_session_factory: sessionmaker[Session]):- session_proxy = scoped_session(sqlite_session_factory)- with patch("controllers.inner_api.workspace.workspace.db.session", session_proxy):- yield session_proxy- session_proxy.remove()---class TestWorkspaceCreatePayload:- """Test WorkspaceCreatePayload Pydantic model validation"""-- def test_valid_payload(self):- """Test valid payload with all fields passes validation"""- data = {- "name": "My Workspace",- "owner_email": "[email protected]",- }- payload = WorkspaceCreatePayload.model_validate(data)- assert payload.name == "My Workspace"- assert payload.owner_email == "[email protected]"-- def test_missing_name_fails_validation(self):- """Test that missing name fails validation"""- data = {"owner_email": "[email protected]"}- with pytest.raises(ValidationError) as exc_info:- WorkspaceCreatePayload.model_validate(data)- assert "name" in str(exc_info.value)-- def test_missing_owner_email_fails_validation(self):- """Test that missing owner_email fails validation"""- data = {"name": "My Workspace"}- with pytest.raises(ValidationError) as exc_info:- WorkspaceCreatePayload.model_validate(data)- assert "owner_email" in str(exc_info.value)---class TestWorkspaceOwnerlessPayload:- """Test WorkspaceOwnerlessPayload Pydantic model validation"""-- def test_valid_payload(self):- """Test valid payload with name passes validation"""- data = {"name": "My Workspace"}- payload = WorkspaceOwnerlessPayload.model_validate(data)- assert payload.name == "My Workspace"-- def test_missing_name_fails_validation(self):- """Test that missing name fails validation"""- data = {}- with pytest.raises(ValidationError) as exc_info:- WorkspaceOwnerlessPayload.model_validate(data)- assert "name" in str(exc_info.value)---class TestWorkspaceMemberPayload:- """Test WorkspaceMemberPayload Pydantic model validation"""-- def test_valid_payload(self):- data = {- "workspace_id": "workspace-id",- "account_id": "account-id",- "email": "[email protected]",- "role": "normal",- "operator_account_id": "operator-id",- }- payload = WorkspaceMemberPayload.model_validate(data)- assert payload.workspace_id == "workspace-id"- assert payload.account_id == "account-id"- assert payload.email == "[email protected]"- assert payload.role == "normal"- assert payload.current is False- assert payload.operator_account_id == "operator-id"-- def test_missing_account_id_fails_validation(self):- data = {"workspace_id": "workspace-id", "email": "[email protected]"}- with pytest.raises(ValidationError) as exc_info:- WorkspaceMemberPayload.model_validate(data)- assert "account_id" in str(exc_info.value)---class TestEnterpriseWorkspace:- """Test EnterpriseWorkspace API endpoint handler logic.-- Uses inspect.unwrap() to bypass auth/setup decorators (tested in test_auth_wraps.py)- and exercise the core business logic directly.- """-- @pytest.fixture- def api_instance(self):- return EnterpriseWorkspace()-- def test_has_post_method(self, api_instance):- """Test that EnterpriseWorkspace has post method"""- assert hasattr(api_instance, "post")- assert callable(api_instance.post)-- @patch("controllers.inner_api.workspace.workspace.TenantService")- def test_post_creates_workspace_with_owner(- self, mock_tenant_svc, api_instance, app: Flask, sqlite_session: Session, database_session- ):- """Test that post() creates a workspace and assigns the owner account"""- # Arrange- account = Account(name="Owner", email="[email protected]")- sqlite_session.add(account)- sqlite_session.commit()-- now = datetime(2025, 1, 1, 12, 0, 0)- tenant = Tenant(name="My Workspace", plan="sandbox", status=TenantStatus.NORMAL)- tenant.id = "tenant-id"- tenant.created_at = now- tenant.updated_at = now- mock_tenant_svc.create_owner_tenant.return_value = tenant-- # Act — unwrap to bypass auth/setup decorators (tested in test_auth_wraps.py)- unwrapped_post = inspect.unwrap(api_instance.post)- payload = {"name": "My Workspace", "owner_email": "[email protected]"}- with app.test_request_context(json=payload):- result = unwrapped_post(api_instance, WorkspaceCreatePayload.model_validate(payload))-- # Assert- assert result["message"] == "enterprise workspace created."- assert result["tenant"]["id"] == "tenant-id"- assert result["tenant"]["name"] == "My Workspace"- mock_tenant_svc.create_owner_tenant.assert_called_once()- call_args = mock_tenant_svc.create_owner_tenant.call_args- assert call_args.args[0].id == account.id- assert call_args.kwargs == {- "name": "My Workspace",- "is_from_dashboard": True,- "session": database_session(),- }-- @pytest.mark.usefixtures("database_session")- def test_post_returns_404_when_owner_not_found(self, api_instance, app: Flask):- """Test that post() returns 404 when the owner account does not exist"""- # Act- unwrapped_post = inspect.unwrap(api_instance.post)- payload = {"name": "My Workspace", "owner_email": "[email protected]"}- with app.test_request_context(json=payload):- result = unwrapped_post(api_instance, WorkspaceCreatePayload.model_validate(payload))-- # Assert- assert result == ({"message": "owner account not found."}, 404)+from services.workspace.contracts import CreatedWorkspace, WorkspaceMembership+from services.workspace.provisioning_service import WorkspaceProvisioningService+from services.workspace.service import WorkspaceQueryService, WorkspaceService-class TestEnterpriseWorkspaceNoOwnerEmail:- """Test EnterpriseWorkspaceNoOwnerEmail API endpoint handler logic.+@dataclass+class Services:+ workspaces: WorkspaceServices- Uses inspect.unwrap() to bypass auth/setup decorators (tested in test_auth_wraps.py)- and exercise the core business logic directly.- """- @pytest.fixture- def api_instance(self):- return EnterpriseWorkspaceNoOwnerEmail()-- def test_has_post_method(self, api_instance):- """Test that endpoint has post method"""- assert hasattr(api_instance, "post")- assert callable(api_instance.post)-- @patch("controllers.inner_api.workspace.workspace.tenant_was_created")- @patch("controllers.inner_api.workspace.workspace.TenantService")- def test_post_creates_ownerless_workspace(- self, mock_tenant_svc, mock_event, api_instance, app: Flask, database_session- ):- """Test that post() creates a workspace without an owner and returns expected fields"""- # Arrange- now = datetime(2025, 1, 1, 12, 0, 0)- tenant = Tenant(- name="My Workspace",- encrypt_public_key="pub-key",- plan="sandbox",- status=TenantStatus.NORMAL,- )- tenant.id = "tenant-id"- tenant.created_at = now- tenant.updated_at = now- mock_tenant_svc.create_tenant.return_value = tenant-- # Act — unwrap to bypass auth/setup decorators (tested in test_auth_wraps.py)- unwrapped_post = inspect.unwrap(api_instance.post)- payload = {"name": "My Workspace"}- with app.test_request_context(json=payload):- result = unwrapped_post(api_instance, WorkspaceOwnerlessPayload.model_validate(payload))-- # Assert- assert result["message"] == "enterprise workspace created."- assert result["tenant"]["id"] == "tenant-id"- assert result["tenant"]["encrypt_public_key"] == "pub-key"- assert result["tenant"]["custom_config"] == {}- mock_tenant_svc.create_tenant.assert_called_once_with(- "My Workspace", is_from_dashboard=True, session=database_session()- )- mock_event.send.assert_called_once_with(tenant)---class TestEnterpriseWorkspaceMember:- """Test EnterpriseWorkspaceMember API endpoint handler logic."""-- @pytest.fixture- def api_instance(self):- return EnterpriseWorkspaceMember()-- def test_has_post_method(self, api_instance):- assert hasattr(api_instance, "post")- assert callable(api_instance.post)-- @patch("controllers.inner_api.workspace.workspace.TenantService")- def test_post_joins_existing_account_to_workspace(self, mock_tenant_svc, api_instance, app: Flask):- membership = TenantAccountJoin(- tenant_id="workspace-id",- account_id="account-id",- role=TenantAccountRole.NORMAL,- )- mock_tenant_svc.join_enterprise_workspace_member.return_value = membership-- unwrapped_post = inspect.unwrap(api_instance.post)- payload = {- "workspace_id": "workspace-id",- "account_id": "account-id",- "email": "[email protected]",- "role": "normal",- "operator_account_id": "operator-id",- }- with app.test_request_context(json=payload):- result = unwrapped_post(api_instance, WorkspaceMemberPayload.model_validate(payload))-- assert result["message"] == "enterprise workspace member joined."- assert result["member"] == {- "workspace_id": "workspace-id",- "account_id": "account-id",- "role": "normal",- }- mock_tenant_svc.join_enterprise_workspace_member.assert_called_once_with(- workspace_id="workspace-id",- account_id="account-id",- email="[email protected]",- role=TenantAccountRole.NORMAL,- operator_account_id="operator-id",- )-- @patch("controllers.inner_api.workspace.workspace.TenantService")- def test_post_returns_404_when_workspace_not_found(self, mock_tenant_svc, api_instance, app: Flask):- mock_tenant_svc.join_enterprise_workspace_member.side_effect = EnterpriseWorkspaceMemberWorkspaceNotFoundError-- unwrapped_post = inspect.unwrap(api_instance.post)- payload = {- "workspace_id": "missing-workspace",- "account_id": "account-id",- "email": "[email protected]",- "role": "normal",- }- with app.test_request_context(json=payload):- result = unwrapped_post(api_instance, WorkspaceMemberPayload.model_validate(payload))-- assert result == ({"message": "workspace not found."}, 404)- mock_tenant_svc.join_enterprise_workspace_member.assert_called_once()-- @patch("controllers.inner_api.workspace.workspace.TenantService")- def test_post_returns_404_when_account_not_found(self, mock_tenant_svc, api_instance, app: Flask):- mock_tenant_svc.join_enterprise_workspace_member.side_effect = EnterpriseWorkspaceMemberAccountNotFoundError-- unwrapped_post = inspect.unwrap(api_instance.post)- payload = {- "workspace_id": "workspace-id",- "account_id": "missing-account",- "email": "[email protected]",- "role": "normal",- }- with app.test_request_context(json=payload):- result = unwrapped_post(api_instance, WorkspaceMemberPayload.model_validate(payload))-- assert result == ({"message": "account not found."}, 404)- mock_tenant_svc.join_enterprise_workspace_member.assert_called_once()-- @pytest.mark.usefixtures("database_session")- def test_post_rejects_owner_role(self, api_instance, app: Flask):- unwrapped_post = inspect.unwrap(api_instance.post)- payload = {- "workspace_id": "workspace-id",- "account_id": "account-id",- "email": "[email protected]",- "role": "owner",- }- with app.test_request_context(json=payload):- result = unwrapped_post(api_instance, WorkspaceMemberPayload.model_validate(payload))-- assert result == ({"message": "cannot join workspace as owner."}, 400)-- @pytest.mark.usefixtures("database_session")- def test_post_rejects_invalid_role(self, api_instance, app: Flask):- unwrapped_post = inspect.unwrap(api_instance.post)- payload = {- "workspace_id": "workspace-id",- "account_id": "account-id",- "email": "[email protected]",- "role": "not-a-role",- }- with app.test_request_context(json=payload):- result = unwrapped_post(api_instance, WorkspaceMemberPayload.model_validate(payload))+def provisioning(monkeypatch: pytest.MonkeyPatch) -> Mock:+ provisioning = Mock(spec=WorkspaceProvisioningService)+ services = WorkspaceServices(+ queries=Mock(spec=WorkspaceQueryService),+ management=Mock(spec=WorkspaceService),+ provisioning=provisioning,+ members=Mock(),+ member_queries=Mock(),+ owner_transfer=Mock(),+ invitations=Mock(),+ identity=Mock(),+ )+ monkeypatch.setattr(controller, "application_services", lambda: Services(services))+ return provisioning- assert result == ({"message": "invalid workspace member role."}, 400)+ ("resource", "payload", "ownerless"),+ [+ (controller.EnterpriseWorkspace, {"name": "Test", "owner_email": "[email protected]"}, False),+ (controller.EnterpriseWorkspaceNoOwnerEmail, {"name": "Test"}, True),+ ],+)+def test_create_serialization(+ app: Flask,+ provisioning: Mock,+ resource: type[+ controller.EnterpriseWorkspace+ | controller.EnterpriseWorkspaceNoOwnerEmail+ | controller.EnterpriseWorkspaceMember+ ],+ payload: dict[str, object],+ ownerless: bool,+) -> None:+ provisioning.create.return_value = CreatedWorkspace(+ "w1", "Test", "sandbox", "normal", datetime(2026, 1, 1), None, "public-key", {"remove_webapp_brand": True}+ )+ with app.test_request_context(method="POST", json=payload):+ body = unwrap(resource.post)(resource())+ assert body["message"] == "enterprise workspace created."+ assert body["tenant"]["created_at"] == "2026-01-01T00:00:00Z"+ assert body["tenant"]["updated_at"] is None+ if ownerless:+ provisioning.create.assert_called_once_with(name="Test")+ assert body["tenant"]["encrypt_public_key"] == "public-key"+ assert body["tenant"]["custom_config"] == {"remove_webapp_brand": True}+ else:+ provisioning.create.assert_called_once_with(name="Test", owner_email="[email protected]")+ assert "encrypt_public_key" not in body["tenant"]+ assert "custom_config" not in body["tenant"]+++def test_owner_missing(app: Flask, provisioning: Mock) -> None:+ provisioning.create.side_effect = WorkspaceOwnerNotFoundError()+ with app.test_request_context(method="POST", json={"name": "Test", "owner_email": "[email protected]"}):+ result = unwrap(controller.EnterpriseWorkspace.post)(controller.EnterpriseWorkspace())+ assert result == ({"message": "owner account not found."}, 404)+++def test_workspace_limit_remains_a_client_error(provisioning: Mock) -> None:+ provisioning.create.side_effect = WorkspacesLimitExceededError("Workspace limit reached")+ http_app = Flask(__name__)+ http_api = Api(http_app, doc=False)+ register_external_error_handlers(http_api)++ class Endpoint(Resource):+ def post(self) -> ResponseReturnValue:+ return unwrap(controller.EnterpriseWorkspace.post)(controller.EnterpriseWorkspace())++ http_api.add_resource(Endpoint, "/workspaces")+ response = http_app.test_client().post("/workspaces", json={"name": "Test", "owner_email": "[email protected]"})+ assert response.status_code == 400+ assert response.json == {"code": "invalid_param", "message": "Workspace limit reached", "status": 400}+++MEMBER = {"workspace_id": "w1", "account_id": "a1", "email": "[email protected]", "current": True}+++def test_join_member(app: Flask, provisioning: Mock) -> None:+ provisioning.join_member.return_value = WorkspaceMembership("w1", "a1", "normal")+ with app.test_request_context(method="POST", json=MEMBER):+ body = unwrap(controller.EnterpriseWorkspaceMember.post)(controller.EnterpriseWorkspaceMember())+ assert body["member"] == {"workspace_id": "w1", "account_id": "a1", "role": "normal"}+ provisioning.join_member.assert_called_once_with(+ workspace_id="w1", account_id="a1", email="[email protected]", role="normal", operator_account_id=None+ )-class TestModelValidateDecorator:- """The handler tests unwrap the view, so this is what covers the decorators themselves."""- @pytest.mark.parametrize(- ("api_cls", "route"),- [- (EnterpriseWorkspace, "/enterprise/workspace"),- (EnterpriseWorkspaceNoOwnerEmail, "/enterprise/workspace/ownerless"),- (EnterpriseWorkspaceMember, "/enterprise/workspace/member"),- ],- )- def test_invalid_body_is_rejected_before_the_handler_runs(- self, app: Flask, api_cls: type[Resource], route: str- ) -> None:- api_instance = api_cls()+ ("error", "message", "status"),+ [+ (AccountNotFoundError(), "account not found.", 404),+ (WorkspaceNotFoundError(), "workspace not found.", 404),+ (InvalidWorkspaceMemberRoleError("invalid workspace member role."), "invalid workspace member role.", 400),+ (InvalidWorkspaceMemberRoleError("cannot join workspace as owner."), "cannot join workspace as owner.", 400),+ ],+)+def test_join_errors(app: Flask, provisioning: Mock, error: Exception, message: str, status: int) -> None:+ provisioning.join_member.side_effect = error+ with app.test_request_context(method="POST", json=MEMBER):+ result = unwrap(controller.EnterpriseWorkspaceMember.post)(controller.EnterpriseWorkspaceMember())+ assert result == ({"message": message}, status)- with (- config_overrides_context(INNER_API=True, INNER_API_KEY="inner-key"),- app.test_request_context(route, method="POST", json={}, headers={"X-Inner-Api-Key": "inner-key"}),- patch("controllers.console.wraps._is_setup_completed", return_value=True),- patch("controllers.inner_api.workspace.workspace.TenantService") as tenant_service,- ):- with pytest.raises(UnprocessableEntity) as exc_info:- api_instance.post()- assert exc_info.value.code == 422- tenant_service.assert_not_called()+ "resource",+ [controller.EnterpriseWorkspace, controller.EnterpriseWorkspaceNoOwnerEmail, controller.EnterpriseWorkspaceMember],+)+def test_invalid_payload_after_admission(+ app: Flask,+ provisioning: Mock,+ config_overrides: Callable[..., None],+ resource: type[+ controller.EnterpriseWorkspace+ | controller.EnterpriseWorkspaceNoOwnerEmail+ | controller.EnterpriseWorkspaceMember+ ],+) -> None:+ config_overrides(INNER_API=True, INNER_API_KEY="secret", DEPLOYMENT_EDITION="CLOUD")+ with app.test_request_context(method="POST", json={}, headers={"X-Inner-Api-Key": "secret"}):+ with pytest.raises(UnprocessableEntity):+ resource().post()+ provisioning.create.assert_not_called()+ provisioning.join_member.assert_not_called()+++def test_inner_api_auth_precedes_payload_parsing(+ app: Flask, provisioning: Mock, config_overrides: Callable[..., None]+) -> None:+ config_overrides(INNER_API=True, INNER_API_KEY="secret", DEPLOYMENT_EDITION="CLOUD")+ with app.test_request_context(method="POST", json={}):+ with pytest.raises(InnerApiUnauthorizedError):+ controller.EnterpriseWorkspace().post()+ provisioning.create.assert_not_called()+++def test_admitted_request_delegates_to_service(+ app: Flask, provisioning: Mock, config_overrides: Callable[..., None]+) -> None:+ config_overrides(INNER_API=True, INNER_API_KEY="secret", DEPLOYMENT_EDITION="CLOUD")+ provisioning.create.return_value = CreatedWorkspace("w", "Test", "sandbox", "normal", None, None, None, {})+ with app.test_request_context(method="POST", json={"name": "Test"}, headers={"X-Inner-Api-Key": "secret"}):+ controller.EnterpriseWorkspaceNoOwnerEmail().post()+ provisioning.create.assert_called_once_with(name="Test")diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_context.py b/api/tests/unit_tests/controllers/openapi/auth/test_context.pyindex ae654e2f599..5e6a350f635 100644--- a/api/tests/unit_tests/controllers/openapi/auth/test_context.py+++ b/api/tests/unit_tests/controllers/openapi/auth/test_context.py@@ -8,8 +8,10 @@ import pytestfrom sqlalchemy.orm import Sessionfrom controllers.openapi.auth.context import Context, RouteContractError+from core.logging.context import clear_request_context, init_request_context+from machinery.context import RequestContextfrom models.model import EndUser-from tests.unit_tests.controllers.openapi.auth._world import make_ctx+from tests.unit_tests.controllers.openapi.auth._world import ACCOUNT_ID, TENANT_ID, make_ctx, make_tenantREADERS: dict[str, Callable[[Context], object]] = {"app": lambda ctx: ctx.app,@@ -18,6 +20,7 @@ READERS: dict[str, Callable[[Context], object]] = {"caller": lambda ctx: ctx.caller,"account": lambda ctx: ctx.account,"end_user": lambda ctx: ctx.end_user,+ "request_context": lambda ctx: ctx.request_context,}@@ -33,3 +36,19 @@ def test_the_caller_is_read_as_what_it_is(sqlite_session: Session) -> None:ctx._caller = EndUser()with pytest.raises(RouteContractError, match="not the Account"):_ = ctx.account+++def test_application_context_keeps_identity_after_request_and_session_end(sqlite_session: Session) -> None:+ init_request_context()+ try:+ ctx = make_ctx(sqlite_session)+ ctx._workspace = make_tenant()+ snapshot = ctx.request_context+ assert snapshot.request_id+ assert snapshot.trace_id+ finally:+ clear_request_context()+ sqlite_session.close()++ assert ctx.request_context == snapshot+ assert snapshot == RequestContext(snapshot.request_id, snapshot.trace_id, ACCOUNT_ID, TENANT_ID)diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_loaders.py b/api/tests/unit_tests/controllers/openapi/auth/test_loaders.pyindex 9c1d222b9ff..c16bebd7e1d 100644--- a/api/tests/unit_tests/controllers/openapi/auth/test_loaders.py+++ b/api/tests/unit_tests/controllers/openapi/auth/test_loaders.py@@ -8,6 +8,7 @@ from flask import Flaskfrom sqlalchemy.orm import Sessionfrom werkzeug.exceptions import Forbidden, NotFound+from controllers.openapi.auth import loadersfrom controllers.openapi.auth.context import Contextfrom controllers.openapi.auth.loaders import (load_app,@@ -18,7 +19,6 @@ from controllers.openapi.auth.loaders import (from controllers.openapi.auth.subjects import Subjectfrom models import Appfrom models.account import TenantAccountRole, TenantStatus-from services.account_service import TenantServicefrom services.app_service import AppServicefrom ._world import (@@ -162,7 +162,7 @@ class TestLoadWorkspaceRole:calls.append(1)return TenantAccountRole.ADMIN- monkeypatch.setattr(TenantService, "get_account_role_in_tenant", _counted)+ monkeypatch.setattr(loaders.application_services().workspaces.members, "get_role", _counted)ctx = Context(_subject(make_account()), sqlite_session, {"app_id": APP_ID})assert load_workspace_role(ctx) is TenantAccountRole.ADMIN@@ -173,7 +173,7 @@ class TestLoadWorkspaceRole:self, sqlite_session: Session, monkeypatch: pytest.MonkeyPatch) -> None:persist(sqlite_session, make_app(), make_tenant(), make_membership(TenantAccountRole.ADMIN))- monkeypatch.setattr(TenantService, "get_account_role_in_tenant", never_reached)+ monkeypatch.setattr(loaders.application_services().workspaces.members, "get_role", never_reached)ctx = Context(_subject(), sqlite_session, {"app_id": APP_ID})with pytest.raises(NotFound, match="workspace not found"):diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_pipelines.py b/api/tests/unit_tests/controllers/openapi/auth/test_pipelines.pyindex 0616895adad..9e7bf73090c 100644--- a/api/tests/unit_tests/controllers/openapi/auth/test_pipelines.py+++ b/api/tests/unit_tests/controllers/openapi/auth/test_pipelines.py@@ -13,6 +13,7 @@ from werkzeug.exceptions import Forbidden, Unauthorizedfrom controllers.openapi._catalog import CATALOG_HEADER, catalog_forfrom controllers.openapi._errors import CatalogStale+from controllers.openapi.auth import loadersfrom controllers.openapi.auth.context import Contextfrom controllers.openapi.auth.pipelines import (_PIPELINES,@@ -34,7 +35,6 @@ from controllers.openapi.auth.subjects import _SUBJECT_CLASSES, AccountSubject,from enums import DeploymentEditionfrom libs.oauth_bearer import AuthContext, try_get_auth_ctxfrom machinery.context import RequestContext-from services.account_service import AccountService, TenantServicefrom services.app_service import AppServicefrom services.enterprise.enterprise_service import WebAppAccessMode@@ -199,8 +199,16 @@ def test_the_requirements_that_share_a_datum_fetch_it_once(with (app.test_request_context(f"/openapi/v1/apps/{APP_ID}", headers=_current_catalog(app)),patch.object(AppService, "get_app_by_id", wraps=AppService.get_app_by_id) as app_fetch,- patch.object(TenantService, "get_tenant_by_id", wraps=TenantService.get_tenant_by_id) as workspace_fetch,- patch.object(AccountService, "get_account_by_id", wraps=AccountService.get_account_by_id) as caller_fetch,+ patch.object(+ loaders.application_services().workspaces.identity,+ "get_workspace",+ wraps=loaders.application_services().workspaces.identity.get_workspace,+ ) as workspace_fetch,+ patch.object(+ loaders.application_services().accounts.identity,+ "get_account_by_id",+ wraps=loaders.application_services().accounts.identity.get_account_by_id,+ ) as caller_fetch,):_run(AccountPipeline(),diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_router.py b/api/tests/unit_tests/controllers/openapi/auth/test_router.pyindex 91161dc0d9f..4359a9e065c 100644--- a/api/tests/unit_tests/controllers/openapi/auth/test_router.py+++ b/api/tests/unit_tests/controllers/openapi/auth/test_router.py@@ -320,7 +320,9 @@ def test_an_account_token_reaches_the_view_with_a_resolved_context(def _rename_handler(*, ctx: Context) -> str:- ctx.caller.name = "renamed"+ account = ctx.session.get(Account, ctx.caller.id)+ assert account is not None+ account.name = "renamed"return "ok"diff --git a/api/tests/unit_tests/controllers/openapi/conftest.py b/api/tests/unit_tests/controllers/openapi/conftest.pyindex 9eaf7ba3e9f..2dda092a989 100644--- a/api/tests/unit_tests/controllers/openapi/conftest.py+++ b/api/tests/unit_tests/controllers/openapi/conftest.py@@ -15,6 +15,7 @@ from constants.oauth_bearer import TokenTypefrom controllers.openapi import bp as openapi_bpfrom controllers.openapi._catalog import CATALOG_HEADER, catalog_forfrom enums import DeploymentEdition+from extensions.ext_application_services import ApplicationServicesfrom libs.oauth_bearer import AuthContextfrom models import Account, App, Tenant, TenantAccountJoinfrom models.account import AccountStatus, TenantAccountRole, TenantStatus@@ -122,3 +123,19 @@ def admitted_bearer(member_id=str(uuid.uuid4()),headers={"Authorization": "Bearer dfoa_admitted", CATALOG_HEADER: catalog_for(openapi_app)[1]},)++[email protected](autouse=True)+def _account_services(monkeypatch: pytest.MonkeyPatch, account_application_services: ApplicationServices) -> None:+ from controllers.openapi import apps, apps_permitted_external, workspaces+ from controllers.openapi.auth import loaders, requirements, subjects++ for module in (+ apps,+ apps_permitted_external,+ workspaces,+ loaders,+ requirements,+ subjects,+ ):+ monkeypatch.setattr(module, "application_services", lambda: account_application_services)diff --git a/api/tests/unit_tests/controllers/openapi/test_app_dsl.py b/api/tests/unit_tests/controllers/openapi/test_app_dsl.pyindex 709b4f76651..216ba150b2a 100644--- a/api/tests/unit_tests/controllers/openapi/test_app_dsl.py+++ b/api/tests/unit_tests/controllers/openapi/test_app_dsl.py@@ -11,7 +11,7 @@ from controllers.openapi.app_dsl import AppDslImportApi, AppDslImportConfirmApifrom controllers.openapi.auth.spec import EndpointSpecfrom machinery.context import RequestContextfrom services.entities.dsl_entities import Import, ImportStatus-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom tests.unit_tests.controllers.conftest import ControllerTestServicesdiff --git a/api/tests/unit_tests/controllers/openapi/test_auth_matrix.py b/api/tests/unit_tests/controllers/openapi/test_auth_matrix.pyindex 4137703e33c..1146f9b36e6 100644--- a/api/tests/unit_tests/controllers/openapi/test_auth_matrix.py+++ b/api/tests/unit_tests/controllers/openapi/test_auth_matrix.py@@ -79,12 +79,14 @@ from constants.oauth_bearer import Scope, TokenTypefrom controllers.common.rbac import PlainApp, RBACCheck, RBACPermission, Workspacefrom controllers.openapi import bp as openapi_bpfrom controllers.openapi._catalog import CATALOG_HEADER, catalog_for+from controllers.openapi.auth import subjectsfrom controllers.openapi.auth.requirements import (CheckAppAccess,CheckAppApiEnabled,CheckRBACPermission,CheckScope,CheckSubject,+ CheckWorkspaceInvitationQuota,CheckWorkspaceMember,CheckWorkspaceRole,Requirement,@@ -98,7 +100,6 @@ from models.account import Account, AccountStatus, Tenant, TenantAccountJoin, Tefrom models.enums import EndUserTypefrom models.model import App, EndUserfrom models.oauth import OAuthAccessToken-from services.account_service import AccountServicefrom services.enterprise.enterprise_service import EnterpriseServicefrom services.entities.feature_entities import LicenseStatus, SystemFeatureModelfrom services.rbac_resource_service import RBACResourceService@@ -745,7 +746,7 @@ DECLARED: dict[str, tuple[Requirement, ...]] = {"workspaces.describe": _REQ_ACCOUNT_WORKSPACE_READ,"workspaces.switch": _REQ_ACCOUNT_WORKSPACE_READ_MEMBER,"workspaces.members.list": _REQ_ACCOUNT_WORKSPACE_READ_MEMBER,- "workspaces.members.invite": _REQ_MEMBER_MANAGE,+ "workspaces.members.invite": (*_REQ_MEMBER_MANAGE, CheckWorkspaceInvitationQuota()),"workspaces.members.remove": _REQ_MEMBER_MANAGE,"workspaces.members.update_role": _REQ_ROLE_MANAGE,"app_dsl.import": _REQ_DSL_WORKSPACE,@@ -1104,8 +1105,14 @@ def _run_case(return_value={"data": [], "total": 0, "hasMore": False},))- services = stack.enter_context(patch("controllers.openapi.auth.subjects.application_services"))- services.return_value.app_scoped_end_users.commands.get_or_create_end_user_by_type.side_effect = _end_user+ services = subjects.application_services()+ stack.enter_context(+ patch.object(+ services.app_scoped_end_users.commands,+ "get_or_create_end_user_by_type",+ side_effect=_end_user,+ )+ )stack.enter_context(patch.object(RBACResourceService, "get_app_agent_binding", return_value=None))stack.enter_context(patch.object(RBACResourceService, "get_app_maintainer", return_value=None))stack.enter_context(@@ -1114,7 +1121,13 @@ def _run_case(return_value=scenario.rbac_allows,))- stack.enter_context(patch.object(AccountService, "get_account_by_email", return_value=_webapp_account()))+ stack.enter_context(+ patch.object(+ services.accounts.identity,+ "get_account_by_email",+ return_value=_webapp_account(),+ )+ )client = app.test_client()return contextvars.copy_context().run(lambda: client.open(_url(route, world, scenario, bearer), method=route.method, headers=headers)diff --git a/api/tests/unit_tests/controllers/openapi/test_integration_context.py b/api/tests/unit_tests/controllers/openapi/test_integration_context.pynew file mode 100644index 00000000000..d9087c902ed--- /dev/null+++ b/api/tests/unit_tests/controllers/openapi/test_integration_context.py@@ -0,0 +1,82 @@+"""Keep the integration handler context aligned with request-scoped identity loading."""++import pytest+from sqlalchemy import select+from sqlalchemy.orm import Session, object_session++from controllers.openapi.auth.context import RouteContractError+from controllers.openapi.auth.requirements import CheckWorkspaceMember+from models import TenantAccountJoin+from models.account import TenantAccountRole+from tests.test_containers_integration_tests.controllers.openapi.conftest import context_for+from tests.unit_tests.controllers.openapi.auth._world import (+ ACCOUNT_ID,+ APP_ID,+ OTHER_TENANT_ID,+ TENANT_ID,+ make_account,+ make_app,+ make_membership,+ make_tenant,+ persist,+)++[email protected]("view_args", [{"workspace_id": TENANT_ID}, {"app_id": APP_ID}])+def test_workspace_requirement_binds_fresh_caller_to_requested_workspace(+ sqlite_session: Session, view_args: dict[str, str]+) -> None:+ account = make_account()+ original_workspace = make_tenant(tenant_id=OTHER_TENANT_ID)+ requested_membership = make_membership(TenantAccountRole.ADMIN)+ requested_membership.current = False+ persist(+ sqlite_session,+ account,+ original_workspace,+ make_tenant(),+ make_app(),+ requested_membership,+ TenantAccountJoin(+ tenant_id=OTHER_TENANT_ID,+ account_id=ACCOUNT_ID,+ current=True,+ role=TenantAccountRole.OWNER,+ ),+ )+ account.set_current_tenant_with_session(original_workspace, session=sqlite_session)++ ctx = context_for(+ account,+ session=sqlite_session,+ view_args=view_args,+ requirements=(CheckWorkspaceMember(),),+ )++ assert ctx.account is not account+ assert object_session(ctx.account) is None+ assert ctx.account.current_tenant_id == ctx.workspace.id == TENANT_ID+ assert ctx.account.role == ctx.workspace_role == TenantAccountRole.ADMIN+ assert account.current_tenant_id == OTHER_TENANT_ID+ assert (+ sqlite_session.scalar(+ select(TenantAccountJoin.tenant_id).where(+ TenantAccountJoin.account_id == ACCOUNT_ID, TenantAccountJoin.current.is_(True)+ )+ )+ == OTHER_TENANT_ID+ )+ if "app_id" in view_args:+ assert ctx.app.id == APP_ID+++def test_app_context_without_workspace_requirement_does_not_bind_workspace(sqlite_session: Session) -> None:+ account = make_account()+ persist(sqlite_session, account, make_tenant(), make_app(), make_membership())++ ctx = context_for(account, session=sqlite_session, view_args={"app_id": APP_ID})++ assert ctx.app.id == APP_ID+ assert ctx.account.current_tenant_id is None+ with pytest.raises(RouteContractError, match="workspace was not loaded"):+ _ = ctx.workspacediff --git a/api/tests/unit_tests/controllers/openapi/test_workspaces_members.py b/api/tests/unit_tests/controllers/openapi/test_workspaces_members.pyindex ce2fcbb3d91..c0e1c2f757f 100644--- a/api/tests/unit_tests/controllers/openapi/test_workspaces_members.py+++ b/api/tests/unit_tests/controllers/openapi/test_workspaces_members.py@@ -7,7 +7,7 @@ Coverage:- Domain exception → HTTP code mapping is preserved with the service'soriginal message (so CLI users see what the console user sees)- Response shape matches the Pydantic models-- The invite route actually commits its unit of work+- Invitations persist through the application service and its repositoriesAuth is not exercised here: `@endpoint` resolves the `Context` before thehandler runs, and the allow/deny answers live in `test_auth_matrix.py`. Body@@ -23,7 +23,6 @@ import builtinsimport uuidfrom datetime import UTC, datetimefrom http import HTTPMethod-from types import SimpleNamespacefrom unittest.mock import Mockimport pytest@@ -31,18 +30,15 @@ from flask import Flaskfrom flask.views import MethodViewfrom pydantic import BaseModel, ValidationErrorfrom sqlalchemy import select-from sqlalchemy.orm import Session, sessionmaker+from sqlalchemy.orm import Sessionfrom werkzeug.exceptions import BadRequest, NotFoundfrom werkzeug.test import TestResponsefrom constants.oauth_bearer import TokenTypefrom controllers.openapi import bp as openapi_bpfrom controllers.openapi import workspaces as workspaces_module-from controllers.openapi._catalog import CATALOG_HEADER, catalog_forfrom controllers.openapi._errors import (ErrorBody,- MemberLicenseExceeded,- MemberLimitExceeded,OpenApiErrorCode,)from controllers.openapi._models import MemberInvitePayload, MemberListQuery, MemberRoleUpdatePayload@@ -50,21 +46,22 @@ from controllers.openapi.auth.context import Contextfrom controllers.openapi.auth.loaders import load_caller, load_workspacefrom controllers.openapi.auth.subjects import AccountSubjectfrom controllers.openapi.workspaces import WorkspaceMemberApi, WorkspaceMembersApi, WorkspaceSwitchApi-from enums import DeploymentEditionfrom libs.oauth_bearer import AuthContextfrom models import Account, Tenant, TenantAccountJoinfrom models.account import TenantAccountRole-from services.account_service import TenantService as RealTenantService-from services.errors.account import (+from services.account_errors import AccountNotFoundError, AccountRegisterError+from services.errors.base import NoPermissionError+from services.errors.workspace import (AccountAlreadyInTenantError,- AccountNotLinkTenantError,- AccountRegisterError,CannotOperateSelfError,+ InvalidWorkspaceMemberRoleError,MemberNotInTenantError,- NoPermissionError,RoleAlreadyAssignedError,+ WorkspaceInvitationQuotaError,+ WorkspaceMemberLicenseQuotaError,+ WorkspaceNotLinkedError,)-from tests.unit_tests.config_override import config_overrides_context+from tests.unit_tests.account_domain import AccountDomainfrom tests.unit_tests.controllers.openapi.conftest import AdmittedWorldfrom tests.unit_tests.model_factories import make_account, make_tenant@@ -154,20 +151,6 @@ def _persist_caller(session: Session, account_id: uuid.UUID) -> None:session.commit()-def _tenant_service(**overrides) -> SimpleNamespace:- """Retain domain mutator doubles while delegating reads to the real service."""- methods: dict = {- "switch_tenant": RealTenantService.switch_tenant,- "get_tenant_members": RealTenantService.get_tenant_members,- "remove_member_from_tenant": Mock(),- "update_member_role": Mock(),- "get_tenant_by_id": RealTenantService.get_tenant_by_id,- "find_workspace_for_account": RealTenantService.find_workspace_for_account,- }- methods.update(overrides)- return SimpleNamespace(**methods)--# ---------------------------------------------------------------------------# Payload validation lands at 422 on the wire (unified via @accepts)# ---------------------------------------------------------------------------@@ -287,9 +270,9 @@ def test_switch_404s_when_service_raises_account_not_link_tenant()monkeypatch.setattr(- workspaces_module,- "TenantService",- _tenant_service(switch_tenant=Mock(side_effect=AccountNotLinkTenantError("…"))),+ workspaces_module.application_services().workspaces.management,+ "switch_membership",+ Mock(side_effect=WorkspaceNotLinkedError("…")),)with pytest.raises(NotFound):@@ -399,25 +382,18 @@ def _invite_body(email: str = "[email protected]") -> MemberInvitePayload:return MemberInvitePayload(email=email, role="normal")-def test_invite_happy_path_returns_invite_url_and_member_id(monkeypatch: pytest.MonkeyPatch, database_session: Session):+def test_invite_happy_path_returns_invite_url_and_member_id(+ database_session: Session, account_domain: AccountDomain+) -> None:ws_id = str(uuid.uuid4())acct_id = uuid.uuid4()api = WorkspaceMembersApi()- invited_id = str(uuid.uuid4())_persist_workspace(database_session,ws_id,[(str(acct_id), "[email protected]", TenantAccountRole.OWNER, True)],)- database_session.add(_account(account_id=invited_id, email="[email protected]"))- database_session.commit()-- monkeypatch.setattr(- workspaces_module,- "RegisterService",- SimpleNamespace(invite_new_member=Mock(return_value="tok-123")),- )result = api.post.__handler__(api,@@ -429,167 +405,62 @@ def test_invite_happy_path_returns_invite_url_and_member_id(monkeypatch: pytest.assert result.result == "success"assert result.email == "[email protected]"assert result.role == "normal"- assert result.member_id == invited_id- assert "token=tok-123" in result.invite_url+ invited = account_domain.repository.get(result.member_id)+ assert invited is not None+ assert invited.email == result.email+ assert "token=invitation-token" in result.invite_urlassert "email=new%40example.com" in result.invite_urlassert result.tenant_id == ws_id-def test_invite_commits_the_invitation(- openapi_app: Flask,- sqlite_session_factory: sessionmaker[Session],- monkeypatch: pytest.MonkeyPatch,-):- """`RegisterService.invite_new_member` carries no commit of its own, so the- invitation persists only because the router commits the request's session.- The double stands in for that contract — it writes through the session it- is handed and returns a token — so this fails if the router stops committing.- """- ws_id = str(uuid.uuid4())- acct_id = uuid.uuid4()- invited_id = str(uuid.uuid4())-- with sqlite_session_factory() as setup:- _persist_workspace(- setup,- ws_id,- [(str(acct_id), "[email protected]", TenantAccountRole.OWNER, True)],- )- setup.add(_account(account_id=invited_id, email="[email protected]"))- setup.commit()-- def _invite(*, tenant, email, language, role, inviter, session) -> str:- session.add(TenantAccountJoin(tenant_id=tenant.id, account_id=invited_id, role=TenantAccountRole.NORMAL))- return "tok-persist"-- monkeypatch.setattr(workspaces_module, "RegisterService", SimpleNamespace(invite_new_member=_invite))- monkeypatch.setattr(- "controllers.openapi.auth.router.get_authenticator",- lambda: SimpleNamespace(authenticate=lambda _token: _auth_ctx(acct_id)),- )- monkeypatch.setattr("controllers.openapi.auth.pipelines._mount_flask_login", lambda _user: None)-- response = openapi_app.test_client().post(- f"/openapi/v1/workspaces/{ws_id}/members",+ ("error", "code"),+ [+ (WorkspaceInvitationQuotaError(), OpenApiErrorCode.MEMBER_LIMIT_EXCEEDED),+ (WorkspaceMemberLicenseQuotaError(), OpenApiErrorCode.MEMBER_LICENSE_EXCEEDED),+ ],+)+def test_invitation_quota_admission_preserves_error_contract(+ admitted_bearer: AdmittedWorld,+ account_domain: AccountDomain,+ error: WorkspaceInvitationQuotaError,+ code: OpenApiErrorCode,+) -> None:+ account_domain.delivery.check_invitation_quota.side_effect = error++ response = admitted_bearer.client.post(+ f"/openapi/v1/workspaces/{admitted_bearer.workspace_id}/members",+ headers=admitted_bearer.headers,json={"email": "[email protected]", "role": "normal"},- headers={"Authorization": "Bearer dfoa_matrix", CATALOG_HEADER: catalog_for(openapi_app)[1]},)- assert response.status_code == 201, response.get_json()- with sqlite_session_factory() as verify:- persisted = verify.scalar(- select(TenantAccountJoin).where(- TenantAccountJoin.tenant_id == ws_id,- TenantAccountJoin.account_id == invited_id,- )- )- assert persisted is not None---def _features(- *,- members_size: int = 0,- members_limit: int = 0,- workspace_members_enabled: bool = False,- workspace_members_size: int = 0,- workspace_members_limit: int = 0,-) -> SimpleNamespace:- """Build a feature object matching the surface `_check_member_invite_quota`- reads: `.members.{size,limit}`,- `.workspace_members.{enabled, is_available(N)}`.-- Defaults leave both quotas unrestricted.- """+ assert response.status_code == 403+ assert ErrorBody.model_validate(response.get_json()).code == code+ account_domain.delivery.check_invitation_quota.assert_called_once_with(admitted_bearer.workspace_id)+ assert account_domain.repository.find_by_email("[email protected]") is None+ account_domain.delivery.send.assert_not_called()- def _is_available(n: int) -> bool:- return workspace_members_size + n <= workspace_members_limit- return SimpleNamespace(- members=SimpleNamespace(size=members_size, limit=members_limit),- workspace_members=SimpleNamespace(- enabled=workspace_members_enabled,- size=workspace_members_size,- limit=workspace_members_limit,- is_available=_is_available,- ),- )---@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)-def test_invite_blocked_by_saas_members_cap(monkeypatch: pytest.MonkeyPatch, database_session: Session):- """SaaS billing plan member cap → MemberLimitExceeded (403)."""- ws_id = str(uuid.uuid4())- acct_id = uuid.uuid4()- api = WorkspaceMembersApi()-- _persist_workspace(- database_session,- ws_id,- [(str(acct_id), "[email protected]", TenantAccountRole.OWNER, True)],- )-- invite_mock = Mock()- monkeypatch.setattr(- workspaces_module,- "RegisterService",- SimpleNamespace(invite_new_member=invite_mock),- )- monkeypatch.setattr(- workspaces_module,- "FeatureService",- SimpleNamespace(- get_features=Mock(- return_value=_features(members_size=10, members_limit=10),- ),- ),- )-- with pytest.raises(MemberLimitExceeded):- api.post.__handler__(api, _context(database_session, acct_id, ws_id), workspace_id=ws_id, body=_invite_body())-- invite_mock.assert_not_called()---@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)-def test_invite_blocked_by_ee_workspace_members_license(monkeypatch: pytest.MonkeyPatch, database_session: Session):- """EE License workspace_members cap → MemberLicenseExceeded (403).-- Enterprise member limits come from the license.- """- ws_id = str(uuid.uuid4())- acct_id = uuid.uuid4()- api = WorkspaceMembersApi()-- _persist_workspace(- database_session,- ws_id,- [(str(acct_id), "[email protected]", TenantAccountRole.OWNER, True)],+def test_invitation_permission_rejection_precedes_quota_lookup(+ admitted_bearer: AdmittedWorld, account_domain: AccountDomain, sqlite_session: Session+) -> None:+ membership = sqlite_session.scalar(+ select(TenantAccountJoin).where(TenantAccountJoin.tenant_id == admitted_bearer.workspace_id))+ assert membership is not None+ membership.role = TenantAccountRole.NORMAL+ sqlite_session.commit()- invite_mock = Mock()- monkeypatch.setattr(- workspaces_module,- "RegisterService",- SimpleNamespace(invite_new_member=invite_mock),- )- monkeypatch.setattr(- workspaces_module,- "FeatureService",- SimpleNamespace(- get_features=Mock(- return_value=_features(- workspace_members_enabled=True,- workspace_members_size=5,- workspace_members_limit=5,- ),- ),- ),+ response = admitted_bearer.client.post(+ f"/openapi/v1/workspaces/{admitted_bearer.workspace_id}/members",+ headers=admitted_bearer.headers,+ json={"email": "[email protected]", "role": "normal"},)- with pytest.raises(MemberLicenseExceeded):- api.post.__handler__(api, _context(database_session, acct_id, ws_id), workspace_id=ws_id, body=_invite_body())-- invite_mock.assert_not_called()+ assert response.status_code == 403+ assert ErrorBody.model_validate(response.get_json()).code == OpenApiErrorCode.FORBIDDEN+ account_domain.delivery.check_invitation_quota.assert_not_called()+ account_domain.delivery.send.assert_not_called()@pytest.mark.parametrize(@@ -597,8 +468,9 @@ def test_invite_blocked_by_ee_workspace_members_license(monkeypatch: pytest.Monk[AccountAlreadyInTenantError("already in tenant"),AccountRegisterError("Workspace is not allowed to create."),+ InvalidWorkspaceMemberRoleError("Dataset operators are not enabled."),],- ids=["already_in_tenant", "register_error"],+ ids=["already_in_tenant", "register_error", "invalid_role"],)def test_invite_400_on_registration_refusal(monkeypatch: pytest.MonkeyPatch, database_session: Session, exc: Exception):ws_id = str(uuid.uuid4())@@ -612,9 +484,7 @@ def test_invite_400_on_registration_refusal(monkeypatch: pytest.MonkeyPatch, dat)monkeypatch.setattr(- workspaces_module,- "RegisterService",- SimpleNamespace(invite_new_member=Mock(side_effect=exc)),+ workspaces_module.application_services().workspaces.invitations, "invite", Mock(side_effect=exc))with pytest.raises(BadRequest):@@ -631,7 +501,10 @@ def test_invite_400_on_registration_refusal(monkeypatch: pytest.MonkeyPatch, dat# ----------------------------------------------------------------------------def test_delete_member_happy_path(monkeypatch: pytest.MonkeyPatch, database_session: Session):[email protected]("member_id_format", ["canonical", "uppercase", "hex"])+def test_delete_member_happy_path(+ database_session: Session, account_domain: AccountDomain, member_id_format: str+) -> None:ws_id, member_id = str(uuid.uuid4()), str(uuid.uuid4())acct_id = uuid.uuid4()api = WorkspaceMemberApi()@@ -645,19 +518,14 @@ def test_delete_member_happy_path(monkeypatch: pytest.MonkeyPatch, database_sess],)- remove_mock = Mock()- monkeypatch.setattr(- workspaces_module,- "TenantService",- _tenant_service(remove_member_from_tenant=remove_mock),- )-+ path_member_id = _member_id_variant(member_id, member_id_format)result = api.delete.__handler__(- api, _context(database_session, acct_id, ws_id), workspace_id=ws_id, member_id=member_id+ api, _context(database_session, acct_id, ws_id), workspace_id=ws_id, member_id=path_member_id)assert result.result == "success"- assert remove_mock.called+ assert account_domain.members.get_role(ws_id, member_id) is None+ assert account_domain.repository.get(member_id) is not None@pytest.mark.parametrize(@@ -666,6 +534,7 @@ def test_delete_member_happy_path(monkeypatch: pytest.MonkeyPatch, database_sess(CannotOperateSelfError("cannot operate self"), BadRequest),(NoPermissionError("no permission"), BadRequest),(MemberNotInTenantError("not in tenant"), NotFound),+ (AccountNotFoundError(), NotFound),],)def test_delete_member_exception_mapping(monkeypatch, exc, expected, database_session: Session):@@ -682,17 +551,14 @@ def test_delete_member_exception_mapping(monkeypatch, exc, expected, database_se],)- monkeypatch.setattr(- workspaces_module,- "TenantService",- _tenant_service(remove_member_from_tenant=Mock(side_effect=exc)),- )+ monkeypatch.setattr(workspaces_module.application_services().workspaces.members, "remove", Mock(side_effect=exc))with pytest.raises(expected):api.delete.__handler__(api, _context(database_session, acct_id, ws_id), workspace_id=ws_id, member_id=member_id)-def test_delete_member_404_when_member_missing(database_session: Session):[email protected]("method", ["delete", "patch"])+def test_member_mutation_404_when_account_missing(database_session: Session, method: str) -> None:ws_id, member_id = str(uuid.uuid4()), str(uuid.uuid4())acct_id = uuid.uuid4()api = WorkspaceMemberApi()@@ -703,8 +569,19 @@ def test_delete_member_404_when_member_missing(database_session: Session):[(str(acct_id), "[email protected]", TenantAccountRole.OWNER, True)],)- with pytest.raises(NotFound):- api.delete.__handler__(api, _context(database_session, acct_id, ws_id), workspace_id=ws_id, member_id=member_id)+ ctx = _context(database_session, acct_id, ws_id)+ if method == "delete":+ with pytest.raises(NotFound, match="member not found"):+ api.delete.__handler__(api, ctx, workspace_id=ws_id, member_id=member_id)+ else:+ with pytest.raises(NotFound, match="member not found"):+ api.patch.__handler__(+ api,+ ctx,+ workspace_id=ws_id,+ member_id=member_id,+ body=MemberRoleUpdatePayload(role="admin"),+ )# ---------------------------------------------------------------------------@@ -712,7 +589,10 @@ def test_delete_member_404_when_member_missing(database_session: Session):# ----------------------------------------------------------------------------def test_update_role_happy_path(monkeypatch: pytest.MonkeyPatch, database_session: Session):[email protected]("member_id_format", ["canonical", "uppercase", "hex"])+def test_update_role_happy_path(+ database_session: Session, account_domain: AccountDomain, member_id_format: str+) -> None:ws_id, member_id = str(uuid.uuid4()), str(uuid.uuid4())acct_id = uuid.uuid4()api = WorkspaceMemberApi()@@ -726,24 +606,88 @@ def test_update_role_happy_path(monkeypatch: pytest.MonkeyPatch, database_sessio],)- update_mock = Mock()- monkeypatch.setattr(- workspaces_module,- "TenantService",- _tenant_service(update_member_role=update_mock),- )-result = api.patch.__handler__(api,_context(database_session, acct_id, ws_id),workspace_id=ws_id,- member_id=member_id,+ member_id=_member_id_variant(member_id, member_id_format),body=MemberRoleUpdatePayload(role="admin"),)assert result.result == "success"- args = update_mock.call_args.args- assert args[2] == "admin"+ assert account_domain.members.get_role(ws_id, member_id) == TenantAccountRole.ADMIN+++def _member_id_variant(member_id: str, variant: str) -> str:+ if variant == "uppercase":+ return member_id.upper()+ if variant == "hex":+ return uuid.UUID(member_id).hex+ if variant == "uppercase_hex":+ return uuid.UUID(member_id).hex.upper()+ return member_id++[email protected]("member_id_format", ["canonical", "uppercase", "hex", "uppercase_hex"])+ ("method", "caller_role"), [("DELETE", TenantAccountRole.OWNER), ("PATCH", TenantAccountRole.ADMIN)]+)+def test_member_id_aliases_cannot_bypass_self_operation_guard(+ admitted_bearer: AdmittedWorld,+ database_session: Session,+ account_domain: AccountDomain,+ member_id_format: str,+ method: str,+ caller_role: TenantAccountRole,+) -> None:+ membership = database_session.scalar(+ select(TenantAccountJoin).where(TenantAccountJoin.tenant_id == admitted_bearer.workspace_id)+ )+ assert membership is not None+ account_id = membership.account_id+ membership.role = caller_role+ owner_id = account_id+ if caller_role == TenantAccountRole.ADMIN:+ owner_id = str(uuid.uuid4())+ database_session.add_all(+ [+ _account(owner_id, "[email protected]"),+ TenantAccountJoin(+ tenant_id=admitted_bearer.workspace_id, account_id=owner_id, role=TenantAccountRole.OWNER+ ),+ ]+ )+ database_session.commit()+ path_member_id = _member_id_variant(account_id, member_id_format)++ response = admitted_bearer.client.open(+ f"/openapi/v1/workspaces/{admitted_bearer.workspace_id}/members/{path_member_id}",+ method=method,+ headers=admitted_bearer.headers,+ json={"role": "normal"} if method == "PATCH" else None,+ )++ assert response.status_code == 400+ error = ErrorBody.model_validate(response.get_json())+ assert error.code == OpenApiErrorCode.BAD_REQUEST+ assert error.message == "Cannot operate self."+ assert account_domain.members.get_role(admitted_bearer.workspace_id, account_id) == caller_role+ assert account_domain.members.get_role(admitted_bearer.workspace_id, owner_id) == TenantAccountRole.OWNER+ account_domain.access.member_removed.assert_not_called()+ account_domain.access.change_role.assert_not_called()++[email protected]("method", ["DELETE", "PATCH"])+def test_malformed_member_id_returns_404(admitted_bearer: AdmittedWorld, method: str) -> None:+ response = admitted_bearer.client.open(+ f"/openapi/v1/workspaces/{admitted_bearer.workspace_id}/members/not-a-uuid",+ method=method,+ headers=admitted_bearer.headers,+ json={"role": "admin"} if method == "PATCH" else None,+ )++ assert response.status_code == 404+ assert ErrorBody.model_validate(response.get_json()).message == "member not found"@pytest.mark.parametrize(@@ -752,7 +696,9 @@ def test_update_role_happy_path(monkeypatch: pytest.MonkeyPatch, database_sessio(CannotOperateSelfError("cannot operate self"), BadRequest),(NoPermissionError("no permission"), BadRequest),(RoleAlreadyAssignedError("already"), BadRequest),+ (InvalidWorkspaceMemberRoleError("Dataset operators are not enabled."), BadRequest),(MemberNotInTenantError("not in tenant"), NotFound),+ (AccountNotFoundError(), NotFound),],)def test_update_role_exception_mapping(monkeypatch, exc, expected, database_session: Session):@@ -770,9 +716,7 @@ def test_update_role_exception_mapping(monkeypatch, exc, expected, database_sess)monkeypatch.setattr(- workspaces_module,- "TenantService",- _tenant_service(update_member_role=Mock(side_effect=exc)),+ workspaces_module.application_services().workspaces.members, "update_role", Mock(side_effect=exc))with pytest.raises(expected):diff --git a/api/tests/unit_tests/controllers/service_api/dataset/test_dataset_apis.py b/api/tests/unit_tests/controllers/service_api/dataset/test_dataset_apis.pyindex 30aa4c5b66a..03aebf9a47b 100644--- a/api/tests/unit_tests/controllers/service_api/dataset/test_dataset_apis.py+++ b/api/tests/unit_tests/controllers/service_api/dataset/test_dataset_apis.py@@ -15,7 +15,7 @@ from flask import Flask, requestfrom sqlalchemy.orm import Sessionfrom werkzeug.exceptions import Forbidden, NotFound, UnprocessableEntity-import services+import services.errors.basefrom controllers.service_api.dataset.error import DatasetInUseError, DatasetNameDuplicateError, InvalidActionErrorfrom models.account import Account, Tenant, TenantAccountRolefrom models.dataset import AppDatasetJoin, Dataset, DatasetMetadata, Document@@ -637,7 +637,7 @@ class TestDatasetApiGet:from controllers.service_api.dataset.dataset import DatasetApimock_dataset_svc.get_dataset.return_value = dataset- mock_dataset_svc.check_dataset_permission.side_effect = services.errors.account.NoPermissionError()+ mock_dataset_svc.check_dataset_permission.side_effect = services.errors.base.NoPermissionError()with app.test_request_context(f"/datasets/{dataset.id}",@@ -853,9 +853,7 @@ class TestDocumentStatusApiPatch:from controllers.service_api.dataset.dataset import DocumentStatusApimock_dataset_svc.get_dataset.return_value = dataset- mock_dataset_svc.check_dataset_permission.side_effect = services.errors.account.NoPermissionError(- "No permission"- )+ mock_dataset_svc.check_dataset_permission.side_effect = services.errors.base.NoPermissionError("No permission")with app.test_request_context(f"/datasets/{dataset.id}/documents/status/enable",diff --git a/api/tests/unit_tests/controllers/service_api/dataset/test_hit_testing.py b/api/tests/unit_tests/controllers/service_api/dataset/test_hit_testing.pyindex b1c5a2a6250..047f9d74129 100644--- a/api/tests/unit_tests/controllers/service_api/dataset/test_hit_testing.py+++ b/api/tests/unit_tests/controllers/service_api/dataset/test_hit_testing.py@@ -21,7 +21,7 @@ import pytestfrom flask import Flask, gfrom werkzeug.exceptions import Forbidden, NotFound-import services+import services.errors.basefrom controllers.service_api.dataset.hit_testing import HitTestingApi, HitTestingPayloadfrom models.account import Account, Tenant, TenantAccountRolefrom models.dataset import Dataset@@ -363,9 +363,7 @@ class TestHitTestingApiPost:account = self._account(tenant_id)mock_dataset_svc.get_dataset.return_value = mock_dataset- mock_dataset_svc.check_dataset_permission.side_effect = services.errors.account.NoPermissionError(- "Access denied"- )+ mock_dataset_svc.check_dataset_permission.side_effect = services.errors.base.NoPermissionError("Access denied")mock_ns.payload = {"query": "test query"}with app.test_request_context():diff --git a/api/tests/unit_tests/controllers/service_api/dataset/test_metadata.py b/api/tests/unit_tests/controllers/service_api/dataset/test_metadata.pyindex 55b42a4e355..f84c146df09 100644--- a/api/tests/unit_tests/controllers/service_api/dataset/test_metadata.py+++ b/api/tests/unit_tests/controllers/service_api/dataset/test_metadata.py@@ -19,14 +19,17 @@ Decorator strategy:import uuidfrom inspect import unwrap-from unittest.mock import ANY, patch+from unittest.mock import ANY, Mock, patchimport pytestfrom flask import Flask, request+from flask.typing import ResponseReturnValue+from flask_restx import Api, Resourcefrom sqlalchemy.orm import Sessionfrom werkzeug.exceptions import NotFoundfrom controllers.common.controller_schemas import MetadataUpdatePayload+from controllers.service_api import api as service_apifrom controllers.service_api.dataset import metadata as metadata_modulefrom controllers.service_api.dataset.metadata import (DatasetMetadataBuiltInFieldActionServiceApi,@@ -38,11 +41,66 @@ from controllers.service_api.dataset.metadata import (from models.account import Account, Tenantfrom models.dataset import Datasetfrom models.enums import PermissionEnum+from services.errors.base import NoPermissionErrorfrom services.errors.metadata import MetadataResourceNotFoundErrorfrom services.knowledge.entities.knowledge_entities import MetadataArgs, MetadataOperationData+from services.knowledge.metadata.application import MetadataServicefrom services.knowledge.resource_scope import DatasetRef+ ("error", "status", "code", "message"),+ [+ (NoPermissionError("Access denied"), 400, "invalid_param", "Access denied"),+ (RuntimeError("backend detail"), 500, "unknown", "Internal Server Error"),+ ],+)+def test_metadata_permission_error_http_contract(+ monkeypatch: pytest.MonkeyPatch,+ account: Account,+ mock_dataset: Dataset,+ sqlite_session: Session,+ error: Exception,+ status: int,+ code: str,+ message: str,+) -> None:+ monkeypatch.setattr(metadata_module, "current_user", account)+ monkeypatch.setattr(+ metadata_module.DatasetService,+ "get_dataset_for_tenant",+ Mock(spec=metadata_module.DatasetService.get_dataset_for_tenant, return_value=mock_dataset),+ )+ monkeypatch.setattr(+ metadata_module.DatasetService,+ "check_dataset_permission",+ Mock(spec=metadata_module.DatasetService.check_dataset_permission, side_effect=error),+ )+ metadata = Mock(spec=MetadataService)+ services = Mock()+ services.knowledge.metadata = metadata+ monkeypatch.setattr(metadata_module, "application_services", lambda: services)+ http_app = Flask(__name__)+ http_api = Api(http_app, doc=False)+ http_api.error_handlers = service_api.error_handlers.copy()++ class Endpoint(Resource):+ def post(self) -> ResponseReturnValue:+ return unwrap(DatasetMetadataCreateServiceApi.post)(+ DatasetMetadataCreateServiceApi(),+ MetadataArgs(type="string", name="author"),+ sqlite_session,+ mock_dataset.tenant_id,+ uuid.UUID(mock_dataset.id),+ )++ http_api.add_resource(Endpoint, "/metadata")+ response = http_app.test_client().post("/metadata")+ assert response.status_code == status+ assert response.json == {"code": code, "message": message, "status": status}+ metadata.create_metadata.assert_not_called()++@pytest.fixturedef mock_tenant() -> Tenant:tenant = Tenant(name="Metadata API Tenant")diff --git a/api/tests/unit_tests/core/app/task_pipeline/test_message_cycle_manager_optimization.py b/api/tests/unit_tests/core/app/task_pipeline/test_message_cycle_manager_optimization.pyindex 1277d08699f..283e5159fab 100644--- a/api/tests/unit_tests/core/app/task_pipeline/test_message_cycle_manager_optimization.py+++ b/api/tests/unit_tests/core/app/task_pipeline/test_message_cycle_manager_optimization.py@@ -12,12 +12,13 @@ from sqlalchemy import Engine, event, selectfrom sqlalchemy.orm import Session, sessionmakerfrom core.app.entities.queue_entities import QueueAnnotationReplyEvent, QueueRetrieverResourcesEvent-from core.app.entities.task_entities import MessageStreamResponse, StreamEvent, TaskStateMetadata+from core.app.entities.task_entities import MessageStreamResponse, StreamEvent, TaskStateMetadata, WorkflowTaskStatefrom core.app.task_pipeline import message_cycle_manager as message_cycle_manager_modulefrom core.app.task_pipeline.message_cycle_manager import MessageCycleManagerfrom core.rag.entities import RetrievalSourceMetadatafrom graphon.file import FileTransferMethod, FileTypefrom models import model as model_module+from models.account import Accountfrom models.base import TypeBasefrom models.enums import ConversationFromSource, CreatorUserRole, MessageFileBelongsTofrom models.model import App, Conversation, MessageAnnotation, MessageFile@@ -415,15 +416,12 @@ class TestMessageCycleManagerOptimization:assert conversation.name == (long_query[:47] + "...")assert any(record.levelno == logging.ERROR for record in caplog.records)- def test_handle_annotation_reply_sets_metadata(self, message_cycle_manager, unbound_session: Session):- """Populate task metadata from annotation reply events.-- Args: message_cycle_manager with TaskStateMetadata and a mocked AppAnnotationService.- Returns: The fetched annotation object.- Side effects: Updates metadata.annotation_reply with id and account name.- """- message_cycle_manager._task_state = SimpleNamespace(metadata=TaskStateMetadata())-+ @pytest.mark.parametrize("author_name", ["Alice", "", None])+ def test_handle_annotation_reply_reads_author_in_one_query(+ self, message_cycle_manager, sqlite_session: Session, sqlite_engine: Engine, author_name: str | None+ ):+ """Read annotation content and author metadata together, including deleted authors."""+ message_cycle_manager._task_state = WorkflowTaskState()annotation = MessageAnnotation(app_id="app-id",question="question",@@ -431,34 +429,42 @@ class TestMessageCycleManagerOptimization:account_id="acct-1",)annotation.id = "ann-1"- session = unbound_session-- with (- patch("core.app.task_pipeline.message_cycle_manager.AppAnnotationService") as mock_service,- patch("core.app.task_pipeline.message_cycle_manager.AccountService") as account_service,- ):- mock_service.get_annotation_by_id.return_value = annotation- account_service.get_account_by_id.return_value = SimpleNamespace(name="Alice")-+ sqlite_session.add(annotation)+ if author_name is not None:+ account = Account(name=author_name, email="[email protected]")+ account.id = annotation.account_id+ sqlite_session.add(account)+ sqlite_session.commit()+ sqlite_session.expunge_all()+ queries: list[str] = []++ def capture_sql(_connection, _cursor, statement: str, _parameters, _context, _executemany) -> None:+ queries.append(statement)++ event.listen(sqlite_engine, "before_cursor_execute", capture_sql)+ try:result = message_cycle_manager.handle_annotation_reply(- QueueAnnotationReplyEvent(message_annotation_id="ann-1"), session+ QueueAnnotationReplyEvent(message_annotation_id="ann-1"), sqlite_session)+ finally:+ event.remove(sqlite_engine, "before_cursor_execute", capture_sql)- assert result == annotation+ assert result is not None+ assert result.id == "ann-1"+ assert result.content == "answer"assert message_cycle_manager._task_state.metadata.annotation_reply.id == "ann-1"- assert message_cycle_manager._task_state.metadata.annotation_reply.account.name == "Alice"- account_service.get_account_by_id.assert_called_once_with("acct-1", session=session)+ assert message_cycle_manager._task_state.metadata.annotation_reply.account.name == (+ author_name if author_name is not None else "Dify user"+ )+ assert len(queries) == 1+ assert "LEFT OUTER JOIN accounts" in queries[0]- def test_handle_annotation_reply_returns_none_when_missing(self, message_cycle_manager):+ def test_handle_annotation_reply_returns_none_when_missing(self, message_cycle_manager, sqlite_session: Session):"""Return None and keep metadata unchanged when annotation is not found."""- message_cycle_manager._task_state = SimpleNamespace(metadata=TaskStateMetadata())-- with patch("core.app.task_pipeline.message_cycle_manager.AppAnnotationService") as mock_service:- mock_service.get_annotation_by_id.return_value = None-- result = message_cycle_manager.handle_annotation_reply(- QueueAnnotationReplyEvent(message_annotation_id="missing"), Mock()- )+ message_cycle_manager._task_state = WorkflowTaskState()+ result = message_cycle_manager.handle_annotation_reply(+ QueueAnnotationReplyEvent(message_annotation_id="missing"), sqlite_session+ )assert result is Noneassert message_cycle_manager._task_state.metadata.annotation_reply is Nonediff --git a/api/tests/unit_tests/core/rag/indexing/processor/test_paragraph_index_processor.py b/api/tests/unit_tests/core/rag/indexing/processor/test_paragraph_index_processor.pyindex 2f330e00159..4cf1893869f 100644--- a/api/tests/unit_tests/core/rag/indexing/processor/test_paragraph_index_processor.py+++ b/api/tests/unit_tests/core/rag/indexing/processor/test_paragraph_index_processor.py@@ -17,6 +17,7 @@ from extensions.storage.storage_type import StorageTypefrom graphon.model_runtime.entities.llm_entities import LLMResult, LLMUsagefrom graphon.model_runtime.entities.message_entities import AssistantPromptMessage, ImagePromptMessageContentfrom graphon.model_runtime.entities.model_entities import ModelFeature, ModelType+from models.account import Accountfrom models.dataset import Dataset, DocumentCreatedFrom, DocumentSegment, SegmentAttachmentBindingfrom models.dataset import Document as DatasetDocumentfrom models.enums import CreatorUserRole, DataSourceType@@ -407,9 +408,11 @@ class TestParagraphIndexProcessor:chunk_without_files = SimpleNamespace(content="content-2", files=None)structure = SimpleNamespace(general_chunks=[chunk_with_files, chunk_without_files])session = self.session- account_session = self.session_factory()+ loaded_account = Account(name="User", email="[email protected]")+ load_user = Mock(return_value=loaded_account)with (+ patch("core.rag.index_processor.processor.paragraph_index_processor.load_account", new=load_user),patch("core.rag.index_processor.processor.paragraph_index_processor.MultimodalGeneralStructureChunk.model_validate",return_value=structure,@@ -418,14 +421,6 @@ class TestParagraphIndexProcessor:"core.rag.index_processor.processor.paragraph_index_processor.helper.generate_text_hash",return_value="hash",),- patch(- "core.rag.index_processor.processor.paragraph_index_processor.AccountService.load_user",- return_value=SimpleNamespace(id="user-1"),- ) as load_user,- patch(- "core.rag.index_processor.processor.paragraph_index_processor.session_factory.create_session",- return_value=nullcontext(account_session),- ),patch.object(processor, "_get_content_files", return_value=[AttachmentDocument(page_content="img", metadata={})]) as mock_files,@@ -439,8 +434,9 @@ class TestParagraphIndexProcessor:processor.index(dataset, dataset_document, {"general_chunks": []}, session)assert mock_files.call_count == 1- load_user.assert_called_once_with(dataset_document.created_by, account_session)- assert account_session is not session+ load_user.assert_called_once_with(dataset_document.created_by)+ assert mock_files.call_args.kwargs["current_user"] is loaded_account+ assert mock_files.call_args.kwargs["session"] is sessiondef test_index_multimodal_structure_requires_valid_account(self, processor: ParagraphIndexProcessor, dataset: Dataset, dataset_document: DatasetDocument@@ -457,10 +453,7 @@ class TestParagraphIndexProcessor:"core.rag.index_processor.processor.paragraph_index_processor.helper.generate_text_hash",return_value="hash",),- patch(- "core.rag.index_processor.processor.paragraph_index_processor.AccountService.load_user",- return_value=None,- ),+ patch("core.rag.index_processor.processor.paragraph_index_processor.load_account", return_value=None),):with pytest.raises(ValueError, match="Invalid account"):processor.index(dataset, dataset_document, {"general_chunks": []}, session)diff --git a/api/tests/unit_tests/core/rag/indexing/processor/test_parent_child_index_processor.py b/api/tests/unit_tests/core/rag/indexing/processor/test_parent_child_index_processor.pyindex 32b09e69877..db837981a58 100644--- a/api/tests/unit_tests/core/rag/indexing/processor/test_parent_child_index_processor.py+++ b/api/tests/unit_tests/core/rag/indexing/processor/test_parent_child_index_processor.py@@ -11,6 +11,7 @@ from core.rag.entities import ParentMode, Rule, Segmentationfrom core.rag.index_processor.constant.index_type import IndexTechniqueTypefrom core.rag.index_processor.processor.parent_child_index_processor import ParentChildIndexProcessorfrom core.rag.models.document import AttachmentDocument, ChildDocument, Document+from models.account import Accountfrom models.dataset import ChildChunk, Dataset, DatasetProcessRule, DocumentCreatedFrom, DocumentSegmentfrom models.dataset import Document as DatasetDocumentfrom models.enums import DataSourceType@@ -453,9 +454,11 @@ class TestParentChildIndexProcessor:parent_child_chunks=[SimpleNamespace(parent_content="parent", child_contents=["child"], files=None)],)session = self.session- account_session = self.session_factory()+ loaded_account = Account(name="User", email="[email protected]")+ load_user = Mock(return_value=loaded_account)with (+ patch("core.rag.index_processor.processor.parent_child_index_processor.load_account", new=load_user),patch("core.rag.index_processor.processor.parent_child_index_processor.ParentChildStructureChunk.model_validate",return_value=parent_childs,@@ -464,14 +467,6 @@ class TestParentChildIndexProcessor:"core.rag.index_processor.processor.parent_child_index_processor.helper.generate_text_hash",return_value="hash",),- patch(- "core.rag.index_processor.processor.parent_child_index_processor.AccountService.load_user",- return_value=SimpleNamespace(id="user-1"),- ) as load_user,- patch(- "core.rag.index_processor.processor.parent_child_index_processor.session_factory.create_session",- return_value=nullcontext(account_session),- ),patch.object(processor, "_get_content_files", return_value=[AttachmentDocument(page_content="image", metadata={})]) as mock_files,@@ -485,8 +480,9 @@ class TestParentChildIndexProcessor:processor.index(dataset, dataset_document, {"parent_child_chunks": []}, session)mock_files.assert_called_once()- load_user.assert_called_once_with(dataset_document.created_by, account_session)- assert account_session is not session+ load_user.assert_called_once_with(dataset_document.created_by)+ assert mock_files.call_args.kwargs["current_user"] is loaded_account+ assert mock_files.call_args.kwargs["session"] is sessiondef test_index_raises_when_account_missing(self, processor: ParentChildIndexProcessor, dataset: Dataset, dataset_document: DatasetDocument@@ -505,10 +501,7 @@ class TestParentChildIndexProcessor:"core.rag.index_processor.processor.parent_child_index_processor.helper.generate_text_hash",return_value="hash",),- patch(- "core.rag.index_processor.processor.parent_child_index_processor.AccountService.load_user",- return_value=None,- ),+ patch("core.rag.index_processor.processor.parent_child_index_processor.load_account", return_value=None),):with pytest.raises(ValueError, match="Invalid account"):processor.index(dataset, dataset_document, {"parent_child_chunks": []}, self.session)diff --git a/api/tests/unit_tests/core/rag/indexing/test_index_processor.py b/api/tests/unit_tests/core/rag/indexing/test_index_processor.pyindex 436d9b1280b..a0ea675e96a 100644--- a/api/tests/unit_tests/core/rag/indexing/test_index_processor.py+++ b/api/tests/unit_tests/core/rag/indexing/test_index_processor.py@@ -1,19 +1,72 @@import uuidfrom contextlib import nullcontextfrom types import SimpleNamespace-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, Mock, patch+from flask import Flaskfrom sqlalchemy import eventfrom sqlalchemy.orm import Session, sessionmakerfrom core.rag.index_processor import index_processor as index_processor_modulefrom core.rag.index_processor.constant.index_type import IndexTechniqueTypefrom core.rag.index_processor.index_processor import IndexProcessor+from core.rag.index_processor.processor.paragraph_index_processor import ParagraphIndexProcessor+from core.rag.models.document import AttachmentDocumentfrom core.workflow.nodes.knowledge_index.protocols import Preview, PreviewItem+from extensions.ext_application_services import ApplicationServices+from extensions.ext_login import bind_account_loader+from models.account import Account, Tenant, TenantAccountJoin, TenantAccountRolefrom models.dataset import Dataset, Document, DocumentSegmentfrom models.enums import DataSourceType, DocumentCreatedFrom, SegmentStatus+class TestIndexingAccountLookup:+ def test_indexes_attachments_with_the_registered_account_loader(+ self, sqlite_session: Session, account_application_services: ApplicationServices+ ) -> None:+ app = Flask(__name__)+ bind_account_loader(app, account_application_services.accounts.identity.load_user)+ dataset, document = _persist_dataset_and_document(sqlite_session)+ account = Account(name="Creator", email="[email protected]")+ account.id = document.created_by+ tenant = Tenant(name="Creator workspace")+ tenant.id = dataset.tenant_id+ sqlite_session.add_all(+ [+ account,+ tenant,+ TenantAccountJoin(+ tenant_id=tenant.id, account_id=account.id, role=TenantAccountRole.OWNER, current=True+ ),+ ]+ )+ sqlite_session.commit()+ attachment = AttachmentDocument(page_content="image", metadata={})++ with (+ app.app_context(),+ patch.object(ParagraphIndexProcessor, "_get_content_files", return_value=[attachment]) as content_files,+ patch("core.rag.index_processor.processor.paragraph_index_processor.DatasetDocumentStore", new=Mock()),+ patch("core.rag.index_processor.processor.paragraph_index_processor.Vector", new=Mock()),+ patch(+ "core.rag.index_processor.processor.paragraph_index_processor.calculate_segment_token_counts",+ return_value=[1],+ ),+ ):+ result = IndexProcessor().index_and_clean(+ dataset_id=dataset.id,+ document_id=document.id,+ original_document_id=document.id,+ chunks={"general_chunks": [{"content": "Image content"}]},+ batch="batch-1",+ session=sqlite_session,+ )++ assert result["display_status"] == "completed"+ assert content_files.call_args.kwargs["current_user"].id == account.id+ assert content_files.call_args.kwargs["session"] is sqlite_session++def _persist_dataset_and_document(session: Session,*,diff --git a/api/tests/unit_tests/core/rag/indexing/test_index_processor_factory.py b/api/tests/unit_tests/core/rag/indexing/test_index_processor_factory.pyindex 0fc666dbbfa..d6d5c31e815 100644--- a/api/tests/unit_tests/core/rag/indexing/test_index_processor_factory.py+++ b/api/tests/unit_tests/core/rag/indexing/test_index_processor_factory.py@@ -1,7 +1,7 @@import pytestfrom core.rag.index_processor.constant.index_type import IndexStructureType-from core.rag.index_processor.index_processor_factory import IndexProcessorFactory+from core.rag.index_processor.index_processor import IndexProcessorFactoryfrom core.rag.index_processor.processor.paragraph_index_processor import ParagraphIndexProcessorfrom core.rag.index_processor.processor.parent_child_index_processor import ParentChildIndexProcessorfrom core.rag.index_processor.processor.qa_index_processor import QAIndexProcessordiff --git a/api/tests/unit_tests/extensions/test_ext_application_services.py b/api/tests/unit_tests/extensions/test_ext_application_services.pyindex fabb2648720..320b3eddca0 100644--- a/api/tests/unit_tests/extensions/test_ext_application_services.py+++ b/api/tests/unit_tests/extensions/test_ext_application_services.py@@ -42,15 +42,9 @@ from models.model import (TrialApp,)from models.provider import ProviderCredential+from repositories.account.repository import SQLAlchemyAccountRepositoryfrom repositories.account_activation_repository import SQLAlchemyAccountActivationRepositoryfrom repositories.account_integration_repository import SQLAlchemyAccountIntegrationRepository-from repositories.account_oauth_repository import (- AccountServiceOAuthAccountRegistrationGateway,- AccountServiceOAuthSessionGateway,- AccountServiceOAuthWorkspaceGateway,- RegisterServiceOAuthInvitationGateway,-)-from repositories.account_repository import SQLAlchemyAccountRepositoryfrom repositories.app.site_command_repository import AppSiteCommandRepositoryfrom repositories.app.tracing_config_repository import SQLAlchemyAppTracingConfigRepositoryfrom repositories.app_scoped_end_user_repository import AppScopedEndUserRepo@@ -63,31 +57,37 @@ from repositories.sqlalchemy_api_workflow_run_repository import DifyAPISQLAlchemfrom repositories.upload_file_delivery_repository import UploadFileDeliveryQueryRepositoryfrom repositories.workflow_app_log_query_repository import WorkflowAppLogQueryRepositoryfrom repositories.workflow_run_archive_repository import WorkflowRunArchiveBundleQueryRepository-from services import account_forgot_password_service, audio_provider_gateway, recommended_app_catalog_gateway-from services.account_adapters import (+from repositories.workspace.workspace_repository import WorkspaceRepository+from services import audio_provider_gateway, recommended_app_catalog_gateway+from services.account import forgot_password_service as account_forgot_password_service+from services.account.adapters import (BillingAccountActivationEligibility,BillingWorkspaceMembershipCache,DeploymentWorkspaceInvitePolicy,RBACWorkspaceMemberAccessSync,RedisInvitationTokenStore,)-from services.account_avatar_file_gateway import SQLAlchemyAccountAvatarFileGateway-from services.account_email_registration_adapters import (- AccountServiceRegistrationGateway,+from services.account.email_registration_adapters import (+ AccountLifecycleRegistrationGateway,BillingAccountRegistrationPolicyGateway,RedisEmailRegistrationSecurityGateway,TokenManagerEmailRegistrationTokenGateway,)-from services.account_forgot_password_adapters import (+from services.account.forgot_password_adapters import (RateLimiterForgotPasswordSendLimiter,RedisForgotPasswordSecurityGateway,RedisForgotPasswordTokenGateway,)-from services.account_oauth_adapters import (+from services.account.login_adapters import RedisConsoleAuthSecurityGateway+from services.account.oauth_adapters import (+ AccountActivationOAuthInvitationGateway,+ AccountLifecycleOAuthRegistrationGateway,+ AccountLifecycleOAuthSessionGateway,DeploymentOAuthPolicyGateway,RedisOAuthAccountClaimLock,+ WorkspaceProvisioningOAuthGateway,)-from services.account_service import AccountService+from services.account_avatar_file_gateway import SQLAlchemyAccountAvatarFileGatewayfrom services.app.api_key_service import AppApiKeyServicefrom services.app.creators_platform_gateway import CreatorsPlatformGatewayfrom services.app_generate_service import AppGenerateService@@ -139,7 +139,7 @@ from services.tag_application_service import TagApplicationServicefrom services.tool_file_download_service import ToolFileDownloadServicefrom services.upload_file_delivery_service import UploadFileDeliveryServicefrom services.web_authentication_adapters import (- AccountServiceWebAuthenticationSecurityGateway,+ AccountWebAuthenticationSecurityGateway,PassportWebAppSessionGateway,TokenManagerWebAuthenticationGateway,)@@ -307,6 +307,8 @@ def test_build_application_services_configures_setup_policy(assert services.setup.get_status().completed is setup_completedassert services.oauth_server is not None+ assert isinstance(services.oauth_device._accounts, SQLAlchemyAccountRepository)+ assert isinstance(services.oauth_device._workspaces, WorkspaceRepository)def test_build_application_services_wires_builtin_schema_definitions(@@ -502,8 +504,9 @@ def test_build_application_services_wires_web_authentication_boundary(services.web_authentication._tokens._access_token_expire_minutes== ext_application_services.dify_config.ACCESS_TOKEN_EXPIRE_MINUTES)- assert isinstance(services.web_authentication._security, AccountServiceWebAuthenticationSecurityGateway)- assert services.web_authentication._security._account_service is AccountService+ assert isinstance(services.web_authentication._security, AccountWebAuthenticationSecurityGateway)+ assert isinstance(services.web_authentication._security._password_security, RedisForgotPasswordSecurityGateway)+ assert isinstance(services.web_authentication._security._login_security, RedisConsoleAuthSecurityGateway)assert isinstance(services.web_authentication._app_sessions, PassportWebAppSessionGateway)assert services.web_authentication._app_sessions._sessions is services.webapp_access._accessassert isinstance(services.webapp_access._policy, EnterpriseWebAppAccessPolicyGateway)@@ -694,7 +697,7 @@ def test_build_application_services_wires_education_rate_limiters(sqlite_session_factory: sessionmaker[Session],) -> None:redis = _redis()- with patch("extensions.ext_application_services.RateLimiter") as rate_limiter_type:+ with patch("extensions.application_services.account.RateLimiter") as rate_limiter_type:ext_application_services.build_application_services(database_client=sqlite_session_factory,deployment_edition=DeploymentEdition.COMMUNITY,@@ -756,26 +759,32 @@ def test_build_application_services_wires_account_profile_repository(assert isinstance(email_registration._tokens, TokenManagerEmailRegistrationTokenGateway)assert isinstance(email_registration._security, RedisEmailRegistrationSecurityGateway)assert isinstance(email_registration._account_policy, BillingAccountRegistrationPolicyGateway)- assert isinstance(email_registration._registration, AccountServiceRegistrationGateway)- assert email_registration._registration._session_factory is sqlite_session_factory+ assert isinstance(email_registration._registration, AccountLifecycleRegistrationGateway)+ assert email_registration._registration._accounts is services.accounts.lifecycle+ assert services.workspaces.invitations._accounts is services.accounts.lifecycle+ assert services.workspaces.invitations._members is services.workspaces.members+ assert services.workspaces.invitations._workspaces is services.workspaces.management._workspaces+ assert services.workspaces.provisioning._members is services.workspaces.members+ assert services.accounts.lifecycle._workspaces is services.workspaces.provisioning+ assert services.workspaces.identity._workspaces is services.workspaces.management._workspacesassert services.accounts.education._accounts is accountsassert services.accounts.deletion._accounts is accountsassert services.accounts.authentication._accounts is accounts- assert services.accounts.authentication._workspaces is services.workspace_queries._workspaces+ assert services.accounts.authentication._workspaces is services.workspaces.queries._workspacesassert services.step_by_step_tour._accounts is accounts- assert services.accounts.deletion._memberships is services.workspace_queries._workspaces+ assert services.accounts.deletion._memberships is services.workspaces.queries._workspacesintegrations = services.accounts.integrations._integrationsassert isinstance(integrations, SQLAlchemyAccountIntegrationRepository)assert integrations._session_factory is sqlite_session_factoryoauth = services.accounts.oauthassert oauth._accounts is accountsassert oauth._integrations is integrations- assert oauth._memberships is services.workspace_queries._workspaces- assert isinstance(oauth._invitations, RegisterServiceOAuthInvitationGateway)+ assert oauth._memberships is services.workspaces.queries._workspaces+ assert isinstance(oauth._invitations, AccountActivationOAuthInvitationGateway)assert isinstance(oauth._account_claims, RedisOAuthAccountClaimLock)- assert isinstance(oauth._registration, AccountServiceOAuthAccountRegistrationGateway)- assert isinstance(oauth._workspaces, AccountServiceOAuthWorkspaceGateway)- assert isinstance(oauth._sessions, AccountServiceOAuthSessionGateway)+ assert isinstance(oauth._registration, AccountLifecycleOAuthRegistrationGateway)+ assert isinstance(oauth._workspaces, WorkspaceProvisioningOAuthGateway)+ assert isinstance(oauth._sessions, AccountLifecycleOAuthSessionGateway)assert oauth._sessions is not oauth._workspacesassert isinstance(oauth._registration_policy, DeploymentOAuthPolicyGateway)assert oauth._workspace_policy is oauth._registration_policy@@ -817,7 +826,7 @@ def test_build_application_services_wires_account_activation(redis=_redis(),)- activation = services.account_activation+ activation = services.accounts.activationassert isinstance(activation._tokens, RedisInvitationTokenStore)assert isinstance(activation._accounts, SQLAlchemyAccountActivationRepository)assert activation._accounts._session_factory is sqlite_session_factory@@ -883,7 +892,7 @@ def test_build_application_services_groups_dataset_services_and_reuses_repositorassert services.data_sources.providers._credentials is actor_credentials._credentialsassert services.knowledge.pipeline_generator._datasource_providers is services.data_sources.providersassert notion_resolver._stored_credentials is not notion_resolver._actor_credentials- assert services.workspace_member_queries._members is dataset_access._workspace_roles+ assert services.workspaces.member_queries._members is dataset_access._workspace_rolesdef test_build_application_services_wires_credential_query(diff --git a/api/tests/unit_tests/libs/test_token_manager.py b/api/tests/unit_tests/libs/test_token_manager.pyindex 35d28efbbda..36c8d4ccd21 100644--- a/api/tests/unit_tests/libs/test_token_manager.py+++ b/api/tests/unit_tests/libs/test_token_manager.py@@ -4,7 +4,7 @@ Regression tests for `libs.helper.TokenManager`.`TokenManager` is the storage primitive shared by multiple auth flows, so itmust preserve every metadata field written by the caller. Business-specificvalidation now happens at the callsite boundary (for example,-`AccountService.get_change_email_data`), not inside `TokenManager`.+`TokenManagerChangeEmailTokenGateway.read`), not inside `TokenManager`."""import jsondiff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.tomlindex 21274d824f5..ab2de5bd152 100644--- a/api/tests/unit_tests/pyrefly.toml+++ b/api/tests/unit_tests/pyrefly.toml@@ -122,7 +122,6 @@ project-excludes = ["controllers/console/test_version.py","controllers/console/test_workflow_run_archive.py","controllers/console/test_workspace_account.py",- "controllers/console/test_workspace_members.py","controllers/console/test_wraps.py","controllers/console/workspace/test_accounts.py","controllers/console/workspace/test_agent_providers.py",@@ -135,7 +134,6 @@ project-excludes = ["controllers/console/workspace/test_rbac.py","controllers/console/workspace/test_snippets.py","controllers/console/workspace/test_tool_providers.py",- "controllers/console/workspace/test_workspace.py","controllers/files/test_upload_file_delivery.py","controllers/files/test_tool_files.py","controllers/inner_api/app/test_dsl.py",@@ -146,7 +144,6 @@ project-excludes = ["controllers/inner_api/test_knowledge_retrieval.py","controllers/inner_api/test_mail.py","controllers/inner_api/test_runtime_credentials.py",- "controllers/inner_api/workspace/test_workspace.py","controllers/mcp/test_mcp.py","controllers/openapi/conftest.py","controllers/openapi/test_account.py",diff --git a/api/tests/unit_tests/repositories/account/__init__.py b/api/tests/unit_tests/repositories/account/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/api/tests/unit_tests/repositories/test_account_repository.py b/api/tests/unit_tests/repositories/account/test_repository.pysimilarity index 90%rename from api/tests/unit_tests/repositories/test_account_repository.pyrename to api/tests/unit_tests/repositories/account/test_repository.pyindex c7158b18fff..eb488225a90 100644--- a/api/tests/unit_tests/repositories/test_account_repository.py+++ b/api/tests/unit_tests/repositories/account/test_repository.py@@ -5,8 +5,8 @@ from sqlalchemy.exc import MultipleResultsFoundfrom sqlalchemy.orm import Session, sessionmakerfrom models.account import Account, AccountIntegrate, AccountStatus, InvitationCode, InvitationCodeStatus+from repositories.account.repository import SQLAlchemyAccountRepositoryfrom repositories.account_integration_repository import SQLAlchemyAccountIntegrationRepository-from repositories.account_repository import SQLAlchemyAccountRepositoryfrom services.account_email import normalize_emailfrom services.entities.account_entities import AccountInitialization, AccountPasswordDigest, AccountProfileChangesfrom services.entities.account_login_entities import (@@ -16,7 +16,9 @@ from services.entities.account_login_entities import (def _persist_account(session: Session) -> Account:- account = Account(name="Original", email="[email protected]")+ account = Account(+ name="Original", email="[email protected]", normalized_email=normalize_email("[email protected]")+ )account.id = "account-1"account.interface_language = "en-US"account.interface_theme = "light"@@ -281,6 +283,46 @@ def test_account_repository_finds_email_with_lowercase_fallback(assert account.email == "[email protected]"+def test_account_repository_finds_mixed_case_sso_email_from_lowercase_input(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ """Workspace invitations must resolve the original casing of an SSO identity (CUS-1658)."""+ account = Account(name="SSO User", email="[email protected]", normalized_email=normalize_email("[email protected]"))+ sqlite_session.add(account)+ sqlite_session.commit()+ repository = SQLAlchemyAccountRepository(sqlite_session_factory)++ result = repository.find_by_email("[email protected]")++ assert result is not None+ assert result.id == account.id+++ ("email", "expected_name"),+ [("[email protected]", "Older"), ("[email protected]", "Newer")],+)+def test_account_repository_prefers_exact_email_then_oldest_normalized_match(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+ email: str,+ expected_name: str,+) -> None:+ newer = Account(name="Newer", email="[email protected]", normalized_email=normalize_email("[email protected]"))+ newer.created_at = datetime(2026, 9, 2)+ older = Account(name="Older", email="[email protected]", normalized_email=normalize_email("[email protected]"))+ older.created_at = datetime(2026, 9, 1)+ sqlite_session.add_all([newer, older])+ sqlite_session.commit()+ repository = SQLAlchemyAccountRepository(sqlite_session_factory)++ result = repository.find_by_email(email)++ assert result is not None+ assert result.name == expected_name++def test_account_repositories_resolve_oauth_identity_and_email_fallback(sqlite_session: Session,sqlite_session_factory: sessionmaker[Session],diff --git a/api/tests/unit_tests/repositories/workspace/__init__.py b/api/tests/unit_tests/repositories/workspace/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/api/tests/unit_tests/repositories/test_workspace_member_query_repository.py b/api/tests/unit_tests/repositories/workspace/test_workspace_members.pysimilarity index 57%rename from api/tests/unit_tests/repositories/test_workspace_member_query_repository.pyrename to api/tests/unit_tests/repositories/workspace/test_workspace_members.pyindex 8aacf2a03b1..090e5008ac2 100644--- a/api/tests/unit_tests/repositories/test_workspace_member_query_repository.py+++ b/api/tests/unit_tests/repositories/workspace/test_workspace_members.py@@ -1,10 +1,14 @@+from collections.abc import Mapping, Sequencefrom datetime import datetime+from sqlalchemy import Engine, eventfrom sqlalchemy.orm import Session, sessionmaker+from machinery.context import RequestContextfrom models.account import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccountRole-from repositories.workspace_member_query_repository import WorkspaceMemberQueryRepository-from services.workspace_member_query_service import WorkspaceMemberRecord+from repositories.workspace.workspace_repository import WorkspaceRepository+from services.workspace.contracts import WorkspaceMemberRecord, WorkspaceMemberRole, WorkspaceMemberRoleSubject+from services.workspace.member_service import WorkspaceMemberQueryServicedef make_account(@@ -92,7 +96,7 @@ def test_list_for_workspace_uses_join_membership_and_preserves_account_lifecycle)session.commit()- result = WorkspaceMemberQueryRepository(sqlite_session_factory).list_for_workspace(workspace.id)+ result = WorkspaceRepository(sqlite_session_factory).list_for_workspace(workspace.id)by_id = {member.id: member for member in result}assert set(by_id) == {"active", "uninitialized", "pending", "banned", "closed"}@@ -121,11 +125,85 @@ def test_list_for_workspace_returns_empty_tuple_without_membership(session.add(make_tenant("workspace-1"))session.commit()- result = WorkspaceMemberQueryRepository(sqlite_session_factory).list_for_workspace("workspace-1")+ result = WorkspaceRepository(sqlite_session_factory).list_for_workspace("workspace-1")assert result == ()+def test_dataset_operators_are_filtered_by_sql_within_workspace(+ sqlite_session_factory: sessionmaker[Session], sqlite_engine: Engine+) -> None:+ workspace = make_tenant("workspace-1")+ other = make_tenant("workspace-2")+ created_at = datetime(2026, 1, 1)+ with sqlite_session_factory.begin() as session:+ session.add_all([workspace, other])+ for account_id, tenant_id, role in [+ ("operator", workspace.id, TenantAccountRole.DATASET_OPERATOR),+ ("editor", workspace.id, TenantAccountRole.EDITOR),+ ("foreign-operator", other.id, TenantAccountRole.DATASET_OPERATOR),+ ]:+ session.add(make_account(account_id, status=AccountStatus.ACTIVE, created_at=created_at))+ session.add(TenantAccountJoin(account_id=account_id, tenant_id=tenant_id, role=role))++ queries: list[str] = []++ def capture_sql(_connection, _cursor, statement: str, _parameters, _context, _executemany) -> None:+ queries.append(statement)++ event.listen(sqlite_engine, "before_cursor_execute", capture_sql)+ try:+ records = WorkspaceRepository(sqlite_session_factory).list_for_workspace(+ workspace.id, role=TenantAccountRole.DATASET_OPERATOR+ )+ finally:+ event.remove(sqlite_engine, "before_cursor_execute", capture_sql)++ assert [record.id for record in records] == ["operator"]+ assert len(queries) == 1+ assert "tenant_account_joins.role =" in queries[0].partition("WHERE")[2]+++def test_member_queries_observe_committed_roles_and_release_session_before_role_resolution(+ sqlite_session_factory: sessionmaker[Session], sqlite_engine: Engine+) -> None:+ with sqlite_session_factory.begin() as session:+ session.add(make_tenant("workspace"))+ session.add(make_account("member", status=AccountStatus.ACTIVE, created_at=datetime(2026, 1, 1)))+ session.add(TenantAccountJoin(tenant_id="workspace", account_id="member", role=TenantAccountRole.NORMAL))++ checked_out: set[int] = set()++ def checkout(connection: object, _record: object, _proxy: object) -> None:+ checked_out.add(id(connection))++ def checkin(connection: object, _record: object) -> None:+ checked_out.discard(id(connection))++ class RoleResolver:+ def resolve_many(+ self, workspace_id: str, actor_account_id: str, subjects: Sequence[WorkspaceMemberRoleSubject]+ ) -> Mapping[str, Sequence[WorkspaceMemberRole]]:+ assert not checked_out+ assert (workspace_id, actor_account_id) == ("workspace", "actor")+ assert subjects == (WorkspaceMemberRoleSubject("member", "editor"),)+ return {"member": (WorkspaceMemberRole("editor", "Editor"),)}++ event.listen(sqlite_engine, "checkout", checkout)+ event.listen(sqlite_engine, "checkin", checkin)+ try:+ repository = WorkspaceRepository(sqlite_session_factory)+ repository.update_member_role(workspace_id="workspace", account_id="member", role=TenantAccountRole.EDITOR)+ service = WorkspaceMemberQueryService(members=repository, roles=RoleResolver())+ result = service.list_current(RequestContext("request", None, "actor", "workspace"))+ assert result[0].role == "editor"+ assert result[0].roles == (WorkspaceMemberRole("editor", "Editor"),)+ assert not checked_out+ finally:+ event.remove(sqlite_engine, "checkout", checkout)+ event.remove(sqlite_engine, "checkin", checkin)++def test_get_legacy_role_is_scoped_to_workspace_and_account(sqlite_session_factory: sessionmaker[Session],) -> None:@@ -147,7 +225,7 @@ def test_get_legacy_role_is_scoped_to_workspace_and_account(])- repository = WorkspaceMemberQueryRepository(sqlite_session_factory)+ repository = WorkspaceRepository(sqlite_session_factory)assert (repository.get_legacy_role(workspace_id=workspace.id, account_id=account.id)diff --git a/api/tests/unit_tests/repositories/workspace/test_workspace_repository.py b/api/tests/unit_tests/repositories/workspace/test_workspace_repository.pynew file mode 100644index 00000000000..02c17d2be56--- /dev/null+++ b/api/tests/unit_tests/repositories/workspace/test_workspace_repository.py@@ -0,0 +1,184 @@+"""Real SQLite coverage for workspace ownership, persistence and Session lifetime."""++from collections.abc import Sequence+from datetime import datetime, timedelta+from unittest.mock import Mock++import pytest+from sqlalchemy import Engine, event, select+from sqlalchemy.orm import Session, sessionmaker++from machinery.context import RequestContext+from models.account import Account, Tenant, TenantAccountJoin, TenantAccountRole, TenantStatus+from repositories.workspace.workspace_repository import WorkspaceRepository+from services.errors.workspace import WorkspaceNotFoundError, WorkspaceNotLinkedError+from services.workspace.contracts import EffectiveCreditPool, WorkspaceCustomConfig, WorkspaceFeatures+from services.workspace.service import (+ WorkspaceFeatureGateway,+ WorkspaceLogoGateway,+ WorkspaceQueryService,+ WorkspaceService,+)+++def seeded(sqlite_session_factory: sessionmaker[Session]) -> WorkspaceRepository:+ with sqlite_session_factory() as session:+ now = datetime(2026, 1, 1)+ account = Account(name="Member", email="[email protected]")+ account.id = "a1"+ first = Tenant(name="First", status=TenantStatus.NORMAL)+ first.id, first.created_at = ("w1", now - timedelta(days=1))+ second = Tenant(name="Second", status=TenantStatus.NORMAL)+ second.id, second.created_at = ("w2", now)+ archived = Tenant(name="Archived", status=TenantStatus.ARCHIVE)+ archived.id, archived.created_at = ("w3", now)+ session.add_all(+ [+ account,+ first,+ second,+ archived,+ TenantAccountJoin(tenant_id="w1", account_id="a1", role=TenantAccountRole.NORMAL, current=True),+ TenantAccountJoin(tenant_id="w2", account_id="a1", role=TenantAccountRole.EDITOR),+ TenantAccountJoin(tenant_id="w3", account_id="a1", role=TenantAccountRole.NORMAL),+ TenantAccountJoin(tenant_id="w2", account_id="other", role=TenantAccountRole.OWNER),+ ]+ )+ session.commit()+ return WorkspaceRepository(sqlite_session_factory)+++def test_lists_preserve_visibility_order_and_archived_memberships(seeded: WorkspaceRepository) -> None:+ assert [row.id for row in seeded.list_for_account("a1")] == ["w1", "w2"]+ assert seeded.list_for_account("absent") == ()+ assert set(seeded.list_ids_for_account("a1")) == {"w1", "w2", "w3"}+ assert {row.id for row in seeded.list_account_access_workspaces("a1")} == {"w1", "w2", "w3"}+ assert [(row.id, row.name, row.role, row.current) for row in seeded.list_for_device_flow("a1")] == [+ ("w1", "First", "normal", True),+ ("w2", "Second", "editor", False),+ ("w3", "Archived", "normal", False),+ ]+ assert seeded.get_many(()) == ()+ assert seeded.has_active_membership("a1")+ assert not seeded.has_active_for_account("absent")+ page = seeded.list_all(page=1, limit=2)+ assert page.total == 3+ assert page.has_more+ assert seeded.list_all(page=3, limit=2).data == ()+++def test_snapshot_role_is_scoped_to_both_account_and_workspace(seeded: WorkspaceRepository) -> None:+ snapshot = seeded.get_for_account("w2", "a1")+ assert snapshot is not None+ assert snapshot.role == "editor"+ assert snapshot.has_privileged_member+ with pytest.raises(WorkspaceNotFoundError):+ seeded.get_for_account("w1", "other")+ assert seeded.get_for_account("missing", "a1") is None+++def test_switch_updates_only_the_requesting_account(+ seeded: WorkspaceRepository, sqlite_session_factory: sessionmaker[Session]+) -> None:+ seeded.switch(account_id="a1", workspace_id="w2")+ with sqlite_session_factory() as session:+ memberships = session.scalars(select(TenantAccountJoin).where(TenantAccountJoin.account_id == "a1")).all()+ assert [row.tenant_id for row in memberships if row.current] == ["w2"]+ assert next(row for row in memberships if row.tenant_id == "w2").last_opened_at is not None+ other = session.scalar(select(TenantAccountJoin).where(TenantAccountJoin.account_id == "other"))+ assert other is not None+ assert not other.current++[email protected]("workspace", ["w3", "missing"])+def test_switch_rejects_archived_and_unlinked_without_changing_current(+ seeded: WorkspaceRepository, sqlite_session_factory: sessionmaker[Session], workspace: str+) -> None:+ with pytest.raises(WorkspaceNotLinkedError):+ seeded.switch(account_id="a1", workspace_id=workspace)+ with sqlite_session_factory() as session:+ current = session.scalar(+ select(TenantAccountJoin.tenant_id).where(+ TenantAccountJoin.account_id == "a1", TenantAccountJoin.current.is_(True)+ )+ )+ assert current == "w1"+++def test_writes_commit_and_other_accounts_cannot_mutate(+ seeded: WorkspaceRepository, sqlite_session_factory: sessionmaker[Session]+) -> None:+ assert seeded.rename(workspace_id="w1", account_id="a1", name="New").name == "New"+ config = WorkspaceCustomConfig(False, "logo")+ seeded.update_custom_config(workspace_id="w1", account_id="a1", changes=config)+ with pytest.raises(WorkspaceNotFoundError):+ seeded.rename(workspace_id="w1", account_id="other", name="Unauthorized")+ with sqlite_session_factory() as session:+ tenant = session.get(Tenant, "w1")+ assert tenant is not None+ assert tenant.name == "New"+ assert tenant.custom_config_dict == {"remove_webapp_brand": False, "replace_webapp_logo": "logo"}+++def test_write_rolls_back_on_commit_failure(+ seeded: WorkspaceRepository, sqlite_session_factory: sessionmaker[Session]+) -> None:++ def fail_flush(_session: Session, _flush_context: object, _instances: object) -> None:+ raise RuntimeError("write failed")++ event.listen(sqlite_session_factory, "before_flush", fail_flush)+ try:+ with pytest.raises(RuntimeError, match="write failed"):+ seeded.rename(workspace_id="w1", account_id="a1", name="Failed")+ finally:+ event.remove(sqlite_session_factory, "before_flush", fail_flush)+ snapshot = seeded.get_for_account("w1", "a1")+ assert snapshot is not None+ assert snapshot.name == "First"+++def test_sessions_are_closed_before_feature_and_plan_io(+ seeded: WorkspaceRepository, sqlite_session_factory: sessionmaker[Session], sqlite_engine: Engine+) -> None:+ checked_out = set()++ def checkout(connection: object, _record: object, _proxy: object) -> None:+ checked_out.add(id(connection))++ def checkin(connection: object, _record: object) -> None:+ checked_out.discard(id(connection))++ event.listen(sqlite_engine, "checkout", checkout)+ event.listen(sqlite_engine, "checkin", checkin)+ features = Mock(spec=WorkspaceFeatureGateway)++ def get_features(workspace_id: str) -> WorkspaceFeatures:+ assert not checked_out+ with sqlite_session_factory() as session:+ tenant = session.get(Tenant, workspace_id)+ assert tenant is not None+ assert tenant.name == "Committed"+ return WorkspaceFeatures(False, EffectiveCreditPool())++ features.get_features.side_effect = get_features+ service = WorkspaceService(workspaces=seeded, features=features, logos=Mock(spec=WorkspaceLogoGateway))+ context = RequestContext("request", None, "a1", "w1")+ try:+ service.rename(context, "Committed")+ plans = Mock()++ def resolve_many(_ids: Sequence[str]) -> dict[str, str]:+ assert not checked_out+ return {"w1": "team"}++ plans.resolve_many.side_effect = resolve_many+ result = WorkspaceQueryService(workspaces=seeded, plans=plans).list_for_account(context)+ assert result[0].current+ assert result[0].plan == "team"+ assert result[1].plan == "sandbox"+ assert not checked_out+ finally:+ event.remove(sqlite_engine, "checkout", checkout)+ event.remove(sqlite_engine, "checkin", checkin)diff --git a/api/tests/unit_tests/services/account/__init__.py b/api/tests/unit_tests/services/account/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/api/tests/unit_tests/services/test_account_adapters.py b/api/tests/unit_tests/services/account/test_adapters.pysimilarity index 91%rename from api/tests/unit_tests/services/test_account_adapters.pyrename to api/tests/unit_tests/services/account/test_adapters.pyindex 0ef41bea71e..20810f0970b 100644--- a/api/tests/unit_tests/services/test_account_adapters.py+++ b/api/tests/unit_tests/services/account/test_adapters.py@@ -7,7 +7,7 @@ import pytestfrom extensions.ext_redis import RedisClientWrapperfrom libs.helper import RateLimiter-from services.account_adapters import (+from services.account.adapters import (BillingAccountActivationEligibility,BillingAccountEducationGateway,BillingAccountEmailPolicyGateway,@@ -77,7 +77,7 @@ def test_invitation_token_store_revokes_its_redis_key() -> None:def test_billing_eligibility_skips_gateway_when_disabled() -> None:- with patch("services.account_adapters.BillingService.get_email_freeze_type") as get_freeze_type:+ 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@@ -86,7 +86,7 @@ def test_billing_eligibility_skips_gateway_when_disabled() -> None:def test_billing_eligibility_returns_freeze_type_when_enabled() -> None:with patch(- "services.account_adapters.BillingService.get_email_freeze_type",+ "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]")@@ -96,14 +96,14 @@ def test_billing_eligibility_returns_freeze_type_when_enabled() -> None:def test_membership_cache_skips_gateway_when_disabled() -> None:- with patch("services.account_adapters.BillingService.clean_billing_info_cache") as invalidate:+ 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:+ 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")@@ -131,7 +131,7 @@ def test_education_gateway_normalizes_billing_status_timestamp() -> None:gateway = BillingAccountEducationGateway()with patch(- "services.account_adapters.BillingService.EducationIdentity.status",+ "services.account.adapters.BillingService.EducationIdentity.status",return_value={"result": True,"is_student": True,@@ -153,7 +153,7 @@ def test_education_gateway_activates_with_primitive_account_context() -> None:gateway = BillingAccountEducationGateway()with patch(- "services.account_adapters.BillingService.EducationIdentity.activate",+ "services.account.adapters.BillingService.EducationIdentity.activate",return_value={"message": "success"},) as activate:result = gateway.activate(@@ -178,7 +178,7 @@ def test_education_gateway_normalizes_autocomplete_defaults() -> None:gateway = BillingAccountEducationGateway()with patch(- "services.account_adapters.BillingService.EducationIdentity.autocomplete",+ "services.account.adapters.BillingService.EducationIdentity.autocomplete",return_value=None,):result = gateway.autocomplete(keywords="Example", page=0, limit=20)@@ -190,9 +190,9 @@ 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.is_email_in_freeze", return_value=True),patch(- "services.account_adapters.BillingService.get_email_freeze_type",+ "services.account.adapters.BillingService.get_email_freeze_type",return_value="email_domain_suspended",),):@@ -203,7 +203,7 @@ def test_token_gateway_rejects_payload_without_account_binding() -> None:gateway = TokenManagerChangeEmailTokenGateway()with patch(- "services.account_adapters.TokenManager.get_token_data",+ "services.account.adapters.TokenManager.get_token_data",return_value={"token_type": "change_email","email": "[email protected]",@@ -225,7 +225,7 @@ def test_token_gateway_issues_account_bound_state() -> None:)with patch(- "services.account_adapters.TokenManager.generate_token",+ "services.account.adapters.TokenManager.generate_token",return_value="token",) as generate_token:assert gateway.issue(token_data) == "token"@@ -274,7 +274,7 @@ def test_verification_gateway_binds_token_to_the_target_account() -> None:gateway = TokenManagerAccountDeletionVerificationGateway()with patch(- "services.account_adapters.TokenManager.get_token_data",+ "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@@ -285,9 +285,9 @@ def test_verification_gateway_creates_six_digit_account_bound_challenge() -> Nongateway = TokenManagerAccountDeletionVerificationGateway()with (- patch("services.account_adapters.secrets.randbelow", side_effect=[1, 2, 3, 4, 5, 6]),+ patch("services.account.adapters.secrets.randbelow", side_effect=[1, 2, 3, 4, 5, 6]),patch(- "services.account_adapters.TokenManager.generate_token",+ "services.account.adapters.TokenManager.generate_token",return_value="token",) as generate_token,):@@ -307,7 +307,7 @@ def test_verification_notifier_preserves_rate_limit_before_enqueuing_email() ->notifier = CeleryAccountDeletionVerificationNotifier(rate_limiter=limiter)with (- patch("services.account_adapters.send_account_deletion_verification_code") as mail_task,+ patch("services.account.adapters.send_account_deletion_verification_code") as mail_task,pytest.raises(AccountDeletionRateLimitError) as error,):notifier.send(email="[email protected]", code="123456")diff --git a/api/tests/unit_tests/services/account/test_email_registration_adapters.py b/api/tests/unit_tests/services/account/test_email_registration_adapters.pynew file mode 100644index 00000000000..60cd7e9b4c7--- /dev/null+++ b/api/tests/unit_tests/services/account/test_email_registration_adapters.py@@ -0,0 +1,194 @@+from collections.abc import Callable+from unittest.mock import Mock, patch++import pytest+from redis import RedisError+from sqlalchemy.orm import Session++from extensions.ext_redis import RedisClientWrapper+from models.account import Account+from services.account.email_registration_adapters import (+ AccountLifecycleRegistrationGateway,+ BillingAccountRegistrationPolicyGateway,+ RedisEmailRegistrationSecurityGateway,+ TokenManagerEmailRegistrationTokenGateway,+)+from services.account.login_adapters import RedisConsoleAuthSecurityGateway+from services.account.login_service import ConsoleAuthSecurityGateway+from services.account.service import AccountService+from services.account_errors import (+ AccountEmailDomainSuspendedError,+ AccountNormalizedEmailAlreadyInUseError,+ EmailRegistrationSeatsLimitError,+ SeatsLimitExceededError,+)+from services.entities.account_entities import (+ AccountEmailRegistrationPhase,+ AccountEmailRegistrationToken,+ AccountSessionTokens,+)+from tests.unit_tests.account_domain import AccountDomain+++def test_token_gateway_rejects_malformed_payload() -> None:+ gateway = TokenManagerEmailRegistrationTokenGateway()++ with patch(+ "services.account.email_registration_adapters.TokenManager.get_token_data",+ return_value={"email": "[email protected]", "phase": "unknown"},+ ):+ assert gateway.get("token") is None+++def test_token_gateway_issues_verified_registration_state() -> None:+ gateway = TokenManagerEmailRegistrationTokenGateway()+ token_data = AccountEmailRegistrationToken(+ email="[email protected]",+ code="123456",+ phase=AccountEmailRegistrationPhase.REGISTER,+ )++ with patch(+ "services.account.email_registration_adapters.TokenManager.generate_token",+ return_value="token",+ ) as generate_token:+ assert gateway.issue(token_data) == "token"++ generate_token.assert_called_once_with(+ email="[email protected]",+ token_type="email_register",+ additional_data={"code": "123456", "phase": "register"},+ )++[email protected](("count", "limited"), [(0, False), (1, False), (2, True)])+def test_security_gateway_preserves_shared_ip_limit(+ config_overrides: Callable[..., None], count: int, limited: bool+) -> None:+ config_overrides(EMAIL_SEND_IP_LIMIT_PER_MINUTE=1)+ redis = Mock(spec=RedisClientWrapper)+ redis.get.side_effect = [None, str(count), None]+ redis.set.return_value = True+ gateway = RedisEmailRegistrationSecurityGateway(+ redis=redis,+ login_security=Mock(spec=ConsoleAuthSecurityGateway),+ verification_failure_limit=5,+ verification_lockout_duration=600,+ )++ assert gateway.is_ip_limited("127.0.0.1") is limited+ if limited:+ redis.set.assert_called_once_with("email_send_ip_limit_hour:127.0.0.1", 1, ex=600, nx=True)+ else:+ redis.setex.assert_called_once_with("email_send_ip_limit_minute:127.0.0.1", 60, count + 1)+ redis.expire.assert_called_once_with("email_send_ip_limit_minute:127.0.0.1", 60)+++def test_security_gateway_uses_registration_and_login_keys() -> None:+ redis = Mock(spec=RedisClientWrapper)+ redis.get.return_value = 1+ gateway = RedisEmailRegistrationSecurityGateway(+ redis=redis,+ login_security=RedisConsoleAuthSecurityGateway(redis=redis),+ verification_failure_limit=5,+ verification_lockout_duration=600,+ )++ with patch(+ "services.account.login_adapters.RedisConsoleAuthSecurityGateway.reset_login_failures"+ ) as reset_login_error_rate_limit:+ gateway.record_verification_failure("[email protected]")+ gateway.reset_verification_failures("[email protected]")+ gateway.reset_login_failures("[email protected]")++ redis.setex.assert_called_once_with("email_register_error_rate_limit:[email protected]", 600, 2)+ redis.delete.assert_called_once_with("email_register_error_rate_limit:[email protected]")+ reset_login_error_rate_limit.assert_called_once_with("[email protected]")++[email protected](("count", "limited"), [(5, False), (6, True)])+def test_registration_verification_limit_preserves_threshold(count: int, limited: bool) -> None:+ redis = Mock(spec=RedisClientWrapper)+ redis.get.return_value = str(count)+ gateway = RedisEmailRegistrationSecurityGateway(+ redis=redis,+ login_security=Mock(spec=ConsoleAuthSecurityGateway),+ verification_failure_limit=5,+ verification_lockout_duration=600,+ )+ assert gateway.is_verification_limited("[email protected]") is limited+ redis.get.assert_called_once_with("email_register_error_rate_limit:[email protected]")+++def test_registration_security_preserves_behavior_when_redis_is_unavailable() -> None:+ redis = Mock(spec=RedisClientWrapper)+ redis.get.side_effect = RedisError("offline")+ redis.delete.side_effect = RedisError("offline")+ gateway = RedisEmailRegistrationSecurityGateway(+ redis=redis,+ login_security=RedisConsoleAuthSecurityGateway(redis=redis),+ verification_failure_limit=5,+ verification_lockout_duration=600,+ )+ assert gateway.is_ip_limited("127.0.0.1") is False+ assert gateway.is_verification_limited("[email protected]") is False+ gateway.record_verification_failure("[email protected]")+ gateway.reset_verification_failures("[email protected]")+ gateway.reset_login_failures("[email protected]")+++def test_billing_policy_is_disabled_outside_cloud() -> None:+ gateway = BillingAccountRegistrationPolicyGateway(enabled=False)++ with patch("services.account.email_registration_adapters.BillingService.get_email_freeze_type") as freeze_type:+ assert gateway.get_freeze_type("[email protected]") is None++ freeze_type.assert_not_called()+++ ("service_error", "application_error"),+ [+ pytest.param(SeatsLimitExceededError(), EmailRegistrationSeatsLimitError, id="seat-limit"),+ pytest.param(AccountEmailDomainSuspendedError(), AccountEmailDomainSuspendedError, id="suspended-domain"),+ pytest.param(+ AccountNormalizedEmailAlreadyInUseError(),+ AccountNormalizedEmailAlreadyInUseError,+ id="normalized-email-in-use",+ ),+ ],+)+def test_registration_gateway_preserves_domain_errors_and_translates_seat_limit(+ service_error: Exception,+ application_error: type[Exception],+) -> None:+ gateway = AccountLifecycleRegistrationGateway(accounts=Mock(spec=AccountService))++ with patch.object(gateway._accounts, "create_account_and_tenant", side_effect=service_error):+ with pytest.raises(application_error) as raised:+ gateway.create(+ email="[email protected]",+ password="ValidPass123!",+ interface_language="en-US",+ timezone=None,+ ip_address="127.0.0.1",+ )+ if isinstance(service_error, application_error):+ assert raised.value is service_error+ else:+ assert raised.value.__cause__ is service_error+++def test_registration_gateway_uses_account_lifecycle(account_domain: AccountDomain, sqlite_session: Session) -> None:+ gateway = AccountLifecycleRegistrationGateway(accounts=account_domain.accounts)+ account_id = gateway.create(+ email="[email protected]",+ password="ValidPass123!",+ interface_language="en-US",+ timezone=None,+ ip_address="127.0.0.1",+ )+ assert sqlite_session.get(Account, account_id) is not None+ tokens = AccountSessionTokens("access", "refresh", "csrf")+ account_domain.sessions.issue.return_value = tokens+ assert gateway.login(account_id, ip_address="127.0.0.1") == tokensdiff --git a/api/tests/unit_tests/services/test_account_email_registration_service.py b/api/tests/unit_tests/services/account/test_email_registration_service.pysimilarity index 99%rename from api/tests/unit_tests/services/test_account_email_registration_service.pyrename to api/tests/unit_tests/services/account/test_email_registration_service.pyindex 513b727e581..035d32e0dba 100644--- a/api/tests/unit_tests/services/test_account_email_registration_service.py+++ b/api/tests/unit_tests/services/account/test_email_registration_service.py@@ -5,7 +5,7 @@ from unittest.mock import Mockimport pytest-from services.account_email_registration_service import (+from services.account.email_registration_service import (AccountEmailRegistrationService,AccountRegistrationGateway,AccountRegistrationPolicyGateway,diff --git a/api/tests/unit_tests/services/test_account_forgot_password_adapters.py b/api/tests/unit_tests/services/account/test_forgot_password_adapters.pysimilarity index 99%rename from api/tests/unit_tests/services/test_account_forgot_password_adapters.pyrename to api/tests/unit_tests/services/account/test_forgot_password_adapters.pyindex e99d5a48c90..256dbf69f54 100644--- a/api/tests/unit_tests/services/test_account_forgot_password_adapters.py+++ b/api/tests/unit_tests/services/account/test_forgot_password_adapters.py@@ -6,7 +6,7 @@ from typing import castimport pytestfrom extensions.ext_redis import RedisClientWrapper-from services.account_forgot_password_adapters import RedisForgotPasswordTokenGateway+from services.account.forgot_password_adapters import RedisForgotPasswordTokenGatewayfrom services.entities.account_entities import ForgotPasswordResetToken, ForgotPasswordVerificationTokendiff --git a/api/tests/unit_tests/services/test_account_forgot_password_service.py b/api/tests/unit_tests/services/account/test_forgot_password_service.pysimilarity index 96%rename from api/tests/unit_tests/services/test_account_forgot_password_service.pyrename to api/tests/unit_tests/services/account/test_forgot_password_service.pyindex 35762edcb48..e5d54b7517e 100644--- a/api/tests/unit_tests/services/test_account_forgot_password_service.py+++ b/api/tests/unit_tests/services/account/test_forgot_password_service.py@@ -8,7 +8,7 @@ from typing import castimport pytestfrom services import account_errors-from services.account_forgot_password_service import (+from services.account.forgot_password_service import (AccountForgotPasswordService,ForgotPasswordCodeGenerator,ForgotPasswordNotificationGateway,@@ -248,6 +248,19 @@ def test_send_code_normalizes_unknown_account_email() -> None:assert dependencies.notifications.sent[0]["registration_allowed"] is False+def test_web_send_rejects_unknown_account_before_issuing_a_token() -> None:+ dependencies = Dependencies()++ with pytest.raises(account_errors.AccountNotFoundError):+ dependencies.service.send_code(+ email="[email protected]", language="en-US", ip_address="127.0.0.1", require_account=True+ )++ assert dependencies.tokens.issued == []+ assert dependencies.notifications.sent == []+ assert dependencies.send_limits.recorded == []++def test_send_code_stops_at_ip_limit() -> None:dependencies = Dependencies(_account())dependencies.security.ip_limited = Truediff --git a/api/tests/unit_tests/services/account/test_identity.py b/api/tests/unit_tests/services/account/test_identity.pynew file mode 100644index 00000000000..3c7adeb644c--- /dev/null+++ b/api/tests/unit_tests/services/account/test_identity.py@@ -0,0 +1,89 @@+from datetime import datetime, timedelta+from unittest.mock import Mock++import pytest+from redis import RedisError+from sqlalchemy import select+from sqlalchemy.orm import Session, sessionmaker+from werkzeug.exceptions import Unauthorized++from extensions.ext_redis import RedisClientWrapper+from libs.datetime_utils import naive_utc_now+from models.account import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccountRole, TenantStatus+from services.account.adapters import AccountIdentityGateway+from tests.unit_tests.account_domain import AccountDomain++[email protected]("has_normal", [True, False])+def test_identity_resolves_normal_workspace_and_detaches_it(+ account_domain: AccountDomain, sqlite_session_factory: sessionmaker[Session], has_normal: bool+) -> None:+ with sqlite_session_factory.begin() as session:+ account = Account(name="User", email="[email protected]")+ archived = Tenant(name="Archived", status=TenantStatus.ARCHIVE)+ session.add_all(+ [+ account,+ archived,+ TenantAccountJoin(+ account_id=account.id, tenant_id=archived.id, role=TenantAccountRole.NORMAL, current=True+ ),+ ]+ )+ if has_normal:+ normal = Tenant(name="Normal")+ session.add_all(+ [normal, TenantAccountJoin(account_id=account.id, tenant_id=normal.id, role=TenantAccountRole.EDITOR)]+ )+ account_id = account.id+ loaded = account_domain.repository.load_identity(account_id, now=datetime(2026, 1, 1))+ if has_normal:+ assert loaded is not None+ assert loaded.current_tenant is not None+ assert loaded.current_tenant.name == "Normal"+ assert loaded.role == TenantAccountRole.EDITOR+ else:+ assert loaded is None+ with sqlite_session_factory() as session:+ current = session.scalars(select(TenantAccountJoin).where(TenantAccountJoin.current.is_(True))).all()+ assert len(current) == int(has_normal)++[email protected]("redis_claim", [True, False, RedisError("offline")])+def test_activity_refresh_is_gated_but_fails_open(+ account_domain: AccountDomain, sqlite_session: Session, redis_claim: bool | RedisError+) -> None:+ now = naive_utc_now()+ account = Account(name="User", email="[email protected]")+ account.last_active_at = now - timedelta(hours=1)+ tenant = Tenant(name="Normal")+ sqlite_session.add_all(+ [+ account,+ tenant,+ TenantAccountJoin(account_id=account.id, tenant_id=tenant.id, role=TenantAccountRole.OWNER, current=True),+ ]+ )+ sqlite_session.commit()+ account_id, old_active = account.id, account.last_active_at+ redis = Mock(spec=RedisClientWrapper)+ if isinstance(redis_claim, RedisError):+ redis.set.side_effect = redis_claim+ else:+ redis.set.return_value = redis_claim+ gateway = AccountIdentityGateway(accounts=account_domain.repository, redis=redis)+ loaded = gateway.load_user(account_id)+ assert loaded is not None+ sqlite_session.expire_all()+ assert (account.last_active_at > old_active) == (redis_claim is not False)+ assert redis.set.call_args.kwargs == {"ex": 600, "nx": True}+++def test_identity_rejects_banned_and_missing_accounts(account_domain: AccountDomain, sqlite_session: Session) -> None:+ account = Account(name="Banned", email="[email protected]", status=AccountStatus.BANNED)+ sqlite_session.add(account)+ sqlite_session.commit()+ gateway = AccountIdentityGateway(accounts=account_domain.repository, redis=Mock(spec=RedisClientWrapper))+ with pytest.raises(Unauthorized, match="banned"):+ gateway.load_user(account.id)+ assert gateway.load_user("missing") is Nonediff --git a/api/tests/unit_tests/services/test_account_login_adapters.py b/api/tests/unit_tests/services/account/test_login_adapters.pysimilarity index 89%rename from api/tests/unit_tests/services/test_account_login_adapters.pyrename to api/tests/unit_tests/services/account/test_login_adapters.pyindex 0c113377a3b..abd23dd2c5e 100644--- a/api/tests/unit_tests/services/test_account_login_adapters.py+++ b/api/tests/unit_tests/services/account/test_login_adapters.py@@ -13,15 +13,18 @@ from sqlalchemy.orm import Session, sessionmakerfrom extensions.ext_redis import RedisClientWrapperfrom libs.helper import RateLimiterfrom models.account import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccountRole+from repositories.account.repository import SQLAlchemyAccountRepositoryfrom services import account_errors-from services import account_login_adapters as adapters+from services.account import login_adapters as adaptersfrom services.email_code_login_challenge import (EmailCodeLoginChallengeResult,EmailCodeLoginChallengeStatus,EmailCodeLoginChallengeUnavailableError,)-from services.entities.account_login_entities import AuthTokenPair, EmailCodeChallengeStatus, RefreshAccountStatus+from services.entities.account_entities import AccountSessionTokens+from services.entities.account_login_entities import EmailCodeChallengeStatus, RefreshAccountStatusfrom services.turnstile_service import TurnstileChallengeRejectedError, TurnstileUpstreamError+from tests.unit_tests.account_domain import AccountDomainclass FakeRateLimiter(RateLimiter):@@ -99,7 +102,7 @@ def test_session_gateway_owns_refresh_token_storage(monkeypatch: pytest.MonkeyParesult = gateway.issue("account-1")- assert result == AuthTokenPair(access_token="access", refresh_token="refresh", csrf_token="csrf")+ assert result == AccountSessionTokens(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"@@ -112,7 +115,9 @@ def test_session_gateway_resolves_rotates_and_revokes_refresh_tokens(monkeypatchmonkeypatch.setattr(gateway,"_issue",- lambda _account_id: AuthTokenPair(access_token="new-access", refresh_token="new-refresh", csrf_token="csrf"),+ lambda _account_id: AccountSessionTokens(+ access_token="new-access", refresh_token="new-refresh", csrf_token="csrf"+ ),)assert gateway.resolve_refresh_token("refresh") == "account-1"@@ -138,17 +143,15 @@ def test_session_gateway_returns_none_for_unknown_refresh_token() -> None:)-def test_workspace_provisioning_gateway_persists_owner_workspace(+def test_workspace_provisioning_persists_owner_workspace(+ account_domain: AccountDomain,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 = account_domain.provisioning- gateway.create_owner_workspace("account-1")+ gateway.ensure_owner_workspace("account-1")with sqlite_session_factory() as session:membership = session.scalar(select(TenantAccountJoin).where(TenantAccountJoin.account_id == "account-1"))@@ -157,13 +160,13 @@ def test_workspace_provisioning_gateway_persists_owner_workspace(assert session.get(Tenant, membership.tenant_id) is not None-def test_workspace_provisioning_gateway_rejects_missing_account(- sqlite_session_factory: sessionmaker[Session],+def test_workspace_provisioning_rejects_missing_account(+ account_domain: AccountDomain,) -> None:- gateway = adapters.SQLAlchemyConsoleAuthProvisioningGateway(session_factory=sqlite_session_factory)+ gateway = account_domain.provisioningwith pytest.raises(account_errors.AccountNotFoundError):- gateway.create_owner_workspace("missing-account")+ gateway.ensure_owner_workspace("missing-account")@pytest.mark.parametrize(@@ -195,7 +198,9 @@ def test_refresh_preparation_gateway_owns_account_state_query())sqlite_session.commit()- gateway = adapters.SQLAlchemyAccountRefreshPreparationGateway(session_factory=sqlite_session_factory)+ gateway = adapters.SQLAlchemyAccountRefreshPreparationGateway(+ accounts=SQLAlchemyAccountRepository(sqlite_session_factory)+ )assert gateway.prepare("account-1") == expected_status@@ -246,13 +251,11 @@ def test_turnstile_gateway_maps_provider_failures(assert (record.exc_info is not None) is has_exception_info-def test_provisioning_gateway_persists_account_and_workspace_atomically(+def test_provisioning_persists_account_and_workspace_atomically(+ account_domain: AccountDomain,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)+ gateway = account_domain.provisioningaccount_id = gateway.create_with_owner_workspace(email="[email protected]",@@ -271,9 +274,9 @@ def test_provisioning_gateway_persists_account_and_workspace_atomically(assert membership is not None-def test_provisioning_gateway_rejects_equivalent_normalized_email(+def test_provisioning_rejects_equivalent_normalized_email(+ account_domain: AccountDomain,sqlite_session: Session,- sqlite_session_factory: sessionmaker[Session],) -> None:sqlite_session.add(Account(@@ -283,7 +286,7 @@ def test_provisioning_gateway_rejects_equivalent_normalized_email())sqlite_session.commit()- gateway = adapters.SQLAlchemyConsoleAuthProvisioningGateway(session_factory=sqlite_session_factory)+ gateway = account_domain.provisioningwith pytest.raises(account_errors.AccountNormalizedEmailAlreadyInUseError):gateway.create_with_owner_workspace(diff --git a/api/tests/unit_tests/services/test_account_login_service.py b/api/tests/unit_tests/services/account/test_login_service.pysimilarity index 97%rename from api/tests/unit_tests/services/test_account_login_service.pyrename to api/tests/unit_tests/services/account/test_login_service.pyindex 4820c3771fb..77984749a70 100644--- a/api/tests/unit_tests/services/test_account_login_service.py+++ b/api/tests/unit_tests/services/account/test_login_service.py@@ -6,11 +6,10 @@ from datetime import datetimeimport pytestfrom services import account_errors-from services.account_login_service import ConsoleAuthenticationService-from services.entities.account_entities import AccountPasswordDigest+from services.account.login_service import ConsoleAuthenticationService+from services.entities.account_entities import AccountPasswordDigest, AccountSessionTokensfrom services.entities.account_login_entities import (AccountSessionPreparation,- AuthTokenPair,EmailCodeChallengeStatus,EmailCodeLoginCommand,EmailCodeSendCommand,@@ -22,7 +21,7 @@ from services.entities.account_login_entities import ()from services.entities.auth_audit_entities import LoginFailureReason-TOKEN_PAIR = AuthTokenPair(access_token="access", refresh_token="refresh", csrf_token="csrf")+TOKENS = AccountSessionTokens(access_token="access", refresh_token="refresh", csrf_token="csrf")LOGIN_TIME = datetime(2026, 8, 24, 12, 0, 0)@@ -147,9 +146,9 @@ class FakeSessions:refresh_account_id: str | None = "account-1"rotations: list[tuple[str, str]] = field(default_factory=list)- def issue(self, account_id: str) -> AuthTokenPair:+ def issue(self, account_id: str) -> AccountSessionTokens:self.issued.append(account_id)- return TOKEN_PAIR+ return TOKENSdef revoke(self, account_id: str) -> None:self.revoked.append(account_id)@@ -158,9 +157,9 @@ class FakeSessions:assert refresh_token == "old-refresh"return self.refresh_account_id- def rotate(self, *, refresh_token: str, account_id: str) -> AuthTokenPair:+ def rotate(self, *, refresh_token: str, account_id: str) -> AccountSessionTokens:self.rotations.append((refresh_token, account_id))- return TOKEN_PAIR+ return TOKENS@dataclass@@ -202,7 +201,7 @@ class FakeAccountProvisioning:class FakeWorkspaceProvisioning:account_ids: list[str] = field(default_factory=list)- def create_owner_workspace(self, account_id: str) -> None:+ def ensure_owner_workspace(self, account_id: str) -> None:self.account_ids.append(account_id)@@ -344,7 +343,7 @@ def test_password_login_issues_session_and_resets_failures() -> None:result = dependencies.service().login_with_password(_password_command())- assert result.token_pair == TOKEN_PAIR+ assert result.tokens == TOKENSassert dependencies.accounts.lookup_email == "[email protected]"assert dependencies.accounts.completions == [PasswordLoginCompletion(@@ -517,7 +516,7 @@ def test_password_login_tries_lowercase_candidate_after_exact_candidate_passwordresult = dependencies.service().login_with_password(_password_command(email="[email protected]"))- assert result.token_pair == TOKEN_PAIR+ assert result.tokens == TOKENSassert [completion.account_id for completion in dependencies.accounts.completions] == ["lowercase"]assert dependencies.sessions.issued == ["lowercase"]assert dependencies.security.failures == []@@ -530,7 +529,7 @@ def test_password_login_returns_no_workspace_without_creating_one() -> None:result = dependencies.service().login_with_password(_password_command())assert not result.workspace_found- assert result.token_pair is None+ assert result.tokens is Noneassert dependencies.workspaces_provisioning.account_ids == []@@ -762,7 +761,7 @@ def test_email_code_login_creates_workspace_for_existing_account() -> None:result = dependencies.service().login_with_email_code(_email_code_command())- assert result == TOKEN_PAIR+ assert result == TOKENSassert dependencies.workspaces_provisioning.account_ids == ["account-1"]@@ -771,7 +770,7 @@ def test_email_code_login_provisions_new_account() -> None:result = dependencies.service().login_with_email_code(_email_code_command())- assert result == TOKEN_PAIR+ assert result == TOKENSassert dependencies.accounts_provisioning.calls == [{"email": "[email protected]",@@ -805,7 +804,7 @@ def test_logout_and_refresh_delegate_to_session_gateway() -> None:service.logout("account-1")assert dependencies.sessions.revoked == ["account-1"]- assert service.refresh("old-refresh") == TOKEN_PAIR+ assert service.refresh("old-refresh") == TOKENSassert dependencies.refresh_preparation.account_ids == ["account-1"]assert dependencies.sessions.rotations == [("old-refresh", "account-1")]diff --git a/api/tests/unit_tests/services/test_account_oauth_adapters.py b/api/tests/unit_tests/services/account/test_oauth_adapters.pysimilarity index 72%rename from api/tests/unit_tests/services/test_account_oauth_adapters.pyrename to api/tests/unit_tests/services/account/test_oauth_adapters.pyindex 18d5e1068bd..851edac4f3d 100644--- a/api/tests/unit_tests/services/test_account_oauth_adapters.py+++ b/api/tests/unit_tests/services/account/test_oauth_adapters.py@@ -5,26 +5,25 @@ import httpximport pytestfrom redis.exceptions import LockNotOwnedErrorfrom sqlalchemy import func, select-from sqlalchemy.orm import Session, sessionmaker+from sqlalchemy.orm import Sessionfrom libs.oauth import JsonObject, OAuth, OAuthUserInfo-from models.account import Account, AccountStatus, Tenant, TenantAccountJoin-from repositories import account_oauth_repository-from repositories.account_oauth_repository import (- AccountServiceOAuthAccountRegistrationGateway,- AccountServiceOAuthWorkspaceGateway,+from models.account import Account, AccountStatus, Tenant+from services.account import oauth_adapters as account_oauth_adapters+from services.account.oauth_adapters import (+ AccountLifecycleOAuthRegistrationGateway,+ DifyOAuthProviderGateway,+ RedisOAuthAccountClaimLock,+ WorkspaceProvisioningOAuthGateway,)-from services import account_oauth_adaptersfrom services.account_errors import (OAuthIdentityLockUnavailableError,OAuthProviderAuthorizationError,OAuthProviderRequestError,OAuthWorkspaceCreationNotAllowedError,)-from services.account_oauth_adapters import DifyOAuthProviderGateway, RedisOAuthAccountClaimLock-from services.account_service import AccountService, TenantServicefrom services.entities.account_oauth_entities import OAuthAccountRegistration, OAuthAuthorizationRequest, OAuthIdentity-from services.errors.workspace import WorkspacesLimitExceededError+from tests.unit_tests.account_domain import AccountDomainclass StubOAuthClient(OAuth):@@ -194,87 +193,6 @@ def test_account_claim_lock_releases_partial_acquisition_on_failure() -> None:assert failed_lock.release_calls == 0-def test_registration_gateway_creates_only_the_account(- sqlite_session_factory: sessionmaker[Session],- monkeypatch: pytest.MonkeyPatch,-) -> None:- calls: list[tuple[str, str, str, str | None, str | None, bool]] = []-- def create_account(- email: str,- name: str,- interface_language: str,- password: str | None = None,- interface_theme: str = "light",- is_setup: bool | None = False,- timezone: str | None = None,- ip_address: str | None = None,- check_normalized_email: bool = False,- *,- session: Session,- ) -> Account:- del password, interface_theme, is_setup- calls.append((email, name, interface_language, timezone, ip_address, check_normalized_email))- account = Account(- email=email,- name=name,- interface_language=interface_language,- timezone=timezone,- last_login_ip=ip_address,- )- session.add(account)- session.flush()- return account-- def unexpected_default_workspace_join(account_id: str) -> None:- raise AssertionError(account_id)-- monkeypatch.setattr(AccountService, "create_account", create_account)- monkeypatch.setattr(account_oauth_repository, "try_join_default_workspace", unexpected_default_workspace_join)- gateway = AccountServiceOAuthAccountRegistrationGateway(session_factory=sqlite_session_factory)-- account_id = gateway.register(- OAuthAccountRegistration(- email="[email protected]",- name="User",- language="en-US",- timezone="Asia/Singapore",- ip_address="203.0.113.10",- )- )-- assert calls == [("[email protected]", "User", "en-US", "Asia/Singapore", "203.0.113.10", True)]- with sqlite_session_factory() as session:- account = session.get(Account, account_id)- assert account is not None- assert account.status == AccountStatus.ACTIVE- assert account.initialized_at is not None- assert session.scalar(select(func.count()).select_from(Tenant)) == 0- assert session.scalar(select(func.count()).select_from(TenantAccountJoin)) == 0---def test_workspace_gateway_maps_workspace_quota_failure(- sqlite_session_factory: sessionmaker[Session],- monkeypatch: pytest.MonkeyPatch,-) -> None:- with sqlite_session_factory.begin() as session:- account = Account(name="User", email="[email protected]")- session.add(account)- session.flush()- account_id = account.id-- def raise_workspace_limit(account: Account, *, session: Session) -> None:- assert account.id == account_id- assert session.get(Account, account_id) is account- raise WorkspacesLimitExceededError-- monkeypatch.setattr(TenantService, "create_owner_tenant", raise_workspace_limit)- gateway = AccountServiceOAuthWorkspaceGateway(session_factory=sqlite_session_factory)-- with pytest.raises(OAuthWorkspaceCreationNotAllowedError):- gateway.create_owner_workspace(account_id)--def test_provider_gateway_adapts_authorization_and_identity_contracts() -> None:client = StubOAuthClient()gateway = DifyOAuthProviderGateway(provider_name="github", client=client)@@ -316,3 +234,31 @@ def test_provider_gateway_translates_provider_rejection() -> None:assert raised.value.description == "invalid authorization code"assert raised.value.__cause__ is client.failure+++def test_registration_gateway_creates_only_the_account(account_domain: AccountDomain, sqlite_session: Session) -> None:+ gateway = AccountLifecycleOAuthRegistrationGateway(accounts=account_domain.accounts)+ account_id = gateway.register(+ OAuthAccountRegistration(+ email="[email protected]",+ name="User",+ language="en-US",+ timezone="Asia/Singapore",+ ip_address="203.0.113.10",+ )+ )+ account = sqlite_session.get(Account, account_id)+ assert account is not None+ assert account.status == AccountStatus.ACTIVE+ assert account.initialized_at is not None+ assert account.timezone == "Asia/Singapore"+ assert account.last_login_ip == "203.0.113.10"+ assert sqlite_session.scalar(select(func.count()).select_from(Tenant)) == 0+++def test_workspace_gateway_maps_workspace_quota_failure(account_domain: AccountDomain) -> None:+ account = account_domain.accounts.create_account("[email protected]", "User", "en-US")+ account_domain.policy.has_workspace_capacity.return_value = False+ gateway = WorkspaceProvisioningOAuthGateway(workspaces=account_domain.provisioning)+ with pytest.raises(OAuthWorkspaceCreationNotAllowedError):+ gateway.create_owner_workspace(account.id)diff --git a/api/tests/unit_tests/services/test_account_oauth_service.py b/api/tests/unit_tests/services/account/test_oauth_service.pysimilarity index 99%rename from api/tests/unit_tests/services/test_account_oauth_service.pyrename to api/tests/unit_tests/services/account/test_oauth_service.pyindex 9e1a3534702..c930eccdac3 100644--- a/api/tests/unit_tests/services/test_account_oauth_service.py+++ b/api/tests/unit_tests/services/account/test_oauth_service.py@@ -9,6 +9,7 @@ from typing import NoReturnimport pytest+from services.account.oauth_service import AccountOAuthServicefrom services.account_errors import (AccountEmailDomainSuspendedError,AccountEmailFrozenError,@@ -20,7 +21,6 @@ from services.account_errors import (OAuthRegistrationError,OAuthWorkspaceCreationNotAllowedError,)-from services.account_oauth_service import AccountOAuthServicefrom services.entities.account_entities import AccountSessionTokens, AccountSnapshotfrom services.entities.account_oauth_entities import (OAuthAccountRegistration,diff --git a/api/tests/unit_tests/services/account/test_service.py b/api/tests/unit_tests/services/account/test_service.pynew file mode 100644index 00000000000..a719ea5ec9a--- /dev/null+++ b/api/tests/unit_tests/services/account/test_service.py@@ -0,0 +1,223 @@+"""Account lifecycle regressions through application ports and real SQLite Sessions."""++from collections.abc import Callable+from datetime import datetime+from unittest.mock import Mock++import pytest+from sqlalchemy import select+from sqlalchemy.orm import Session, sessionmaker++from models.account import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccountRole, TenantStatus+from models.model import DifySetup+from repositories.installation_state_repository import InstallationStateRepository+from services.account.contracts import SetupInput+from services.account.service import AccountSetupProvisioner+from services.account_errors import (+ AccountEmailDomainSuspendedError,+ AccountLoginError,+ AccountNormalizedEmailAlreadyInUseError,+ AccountNotFoundError,+ AccountPasswordError,+ AccountRegisterError,+ SeatsLimitExceededError,+)+from services.entities.account_entities import AccountSessionTokens+from services.errors.workspace import WorkSpaceNotAllowedCreateError+from tests.unit_tests.account_domain import AccountDomain+++def test_creation_hashes_password_and_keeps_registration_ip(+ account_domain: AccountDomain, sqlite_session: Session+) -> None:+ account = account_domain.accounts.create_account(+ "[email protected]", "New", "en-US", password="Valid123!", ip_address="203.0.113.1"+ )+ stored = sqlite_session.get(Account, account.id)+ assert stored is not None+ assert stored.email == "[email protected]"+ assert stored.normalized_email == "[email protected]"+ assert stored.password != "Valid123!"+ assert stored.last_login_ip == "203.0.113.1"+ assert account.status == "active"+ assert account.initialized_at is None+ assert account_domain.accounts.authenticate("[email protected]", "Valid123!").id == account.id+ with pytest.raises(AccountPasswordError):+ account_domain.accounts.authenticate(account.email, "wrong")+++ ("setting", "value", "error"),+ [+ pytest.param(+ lambda policy: policy.is_registration_allowed, False, AccountNotFoundError, id="registration_disabled"+ ),+ pytest.param(lambda policy: policy.has_account_capacity, False, SeatsLimitExceededError, id="seat_limit"),+ pytest.param(+ lambda policy: policy.get_email_freeze_type,+ "email_domain_suspended",+ AccountEmailDomainSuspendedError,+ id="domain_suspended",+ ),+ pytest.param(lambda policy: policy.get_email_freeze_type, "deleted", AccountRegisterError, id="deleted"),+ ],+)+def test_creation_policy_prevents_persistence(+ account_domain: AccountDomain,+ sqlite_session: Session,+ setting: Callable[[Mock], Mock],+ value: object,+ error: type[Exception],+) -> None:+ setting(account_domain.policy).return_value = value+ with pytest.raises(error):+ account_domain.accounts.create_account("[email protected]", "New", "en-US")+ assert sqlite_session.scalar(select(Account.id)) is None+++def test_setup_bypasses_registration_but_not_seat_limit(account_domain: AccountDomain) -> None:+ account_domain.policy.is_registration_allowed.return_value = False+ account_domain.accounts.create_account("[email protected]", "First", "en-US", is_setup=True)+ account_domain.policy.has_account_capacity.return_value = False+ with pytest.raises(SeatsLimitExceededError):+ account_domain.accounts.create_account("[email protected]", "Second", "en-US", is_setup=True)+++def test_email_collision_is_checked_before_capacity(account_domain: AccountDomain) -> None:+ account_domain.accounts.create_account("[email protected]", "First", "en-US")+ account_domain.policy.has_account_capacity.return_value = False+ with pytest.raises(AccountNormalizedEmailAlreadyInUseError):+ account_domain.accounts.create_account("[email protected]", "Second", "en-US", check_normalized_email=True)++[email protected]("timezone", [None, "Asia/Singapore"])+def test_registration_initializes_and_creates_owner_membership(+ account_domain: AccountDomain, sqlite_session: Session, timezone: str | None+) -> None:+ account = account_domain.accounts.register("[email protected]", "New", language="zh-Hans", timezone=timezone)+ assert account.initialized_at == datetime(2026, 1, 1)+ assert account.timezone == (timezone or "Asia/Shanghai")+ memberships = list(sqlite_session.scalars(select(TenantAccountJoin)))+ assert len(memberships) == 1+ assert memberships[0].account_id == account.id+ assert memberships[0].role == TenantAccountRole.OWNER+ assert not memberships[0].current+ account_domain.policy.try_join_default_workspace.assert_called_once_with(account.id)+++ "setting",+ [+ pytest.param(lambda policy: policy.is_workspace_creation_allowed, id="creation_disabled"),+ pytest.param(lambda policy: policy.has_workspace_capacity, id="workspace_limit"),+ ],+)+def test_registration_without_personal_workspace_still_joins_default(+ account_domain: AccountDomain, sqlite_session: Session, setting: Callable[[Mock], Mock]+) -> None:+ setting(account_domain.policy).return_value = False+ account = account_domain.accounts.register("[email protected]", "New", status="pending")+ assert account.status == "pending"+ assert sqlite_session.scalar(select(Tenant.id)) is None+ account_domain.policy.try_join_default_workspace.assert_called_once_with(account.id)+++def test_personal_workspace_failure_still_attempts_enterprise_join(account_domain: AccountDomain) -> None:+ account_domain.policy.is_workspace_creation_allowed.return_value = False+ with pytest.raises(WorkSpaceNotAllowedCreateError):+ account_domain.accounts.create_account_and_tenant("[email protected]", "New", "en-US")+ account_domain.policy.try_join_default_workspace.assert_called_once()+++def test_existing_archived_membership_prevents_implicit_workspace_creation(+ account_domain: AccountDomain, sqlite_session: Session+) -> None:+ account = account_domain.accounts.create_account("[email protected]", "A", "en-US")+ tenant = Tenant(name="Archived", status=TenantStatus.ARCHIVE)+ sqlite_session.add_all(+ [tenant, TenantAccountJoin(account_id=account.id, tenant_id=tenant.id, role=TenantAccountRole.NORMAL)]+ )+ sqlite_session.commit()+ account_domain.provisioning.create_owner_workspace(account.id, if_missing=True)+ assert list(sqlite_session.scalars(select(Tenant.id))) == [tenant.id]+++def test_login_activates_pending_and_issues_tokens_after_commit(+ account_domain: AccountDomain, sqlite_session: Session+) -> None:+ account = account_domain.accounts.create_account("[email protected]", "A", "en-US", status="pending")+ pair = AccountSessionTokens("access", "refresh", "csrf")++ def issue(account_id: str) -> AccountSessionTokens:+ stored = sqlite_session.get(Account, account_id)+ assert stored is not None+ assert stored.status == AccountStatus.ACTIVE+ assert stored.last_login_ip == "203.0.113.2"+ return pair++ account_domain.sessions.issue.side_effect = issue+ assert account_domain.accounts.login(account.id, ip_address="203.0.113.2") == pair+ with pytest.raises(AccountNotFoundError):+ account_domain.accounts.login("missing", ip_address="203.0.113.2")+++def test_authentication_rejects_banned_account(account_domain: AccountDomain) -> None:+ account_domain.accounts.create_account("[email protected]", "B", "en-US", password="Valid123!", status="banned")+ with pytest.raises(AccountLoginError):+ account_domain.accounts.authenticate("[email protected]", "Valid123!")+++def test_setup_cleans_partial_state_on_failure(+ account_domain: AccountDomain, sqlite_session_factory: sessionmaker[Session], sqlite_session: Session+) -> None:+ class Telemetry:+ def report(self) -> None:+ pytest.fail("Failed setup cannot report success")++ installation = InstallationStateRepository(session_factory=sqlite_session_factory)+ account_domain.policy.has_workspace_capacity.return_value = False+ provisioner = AccountSetupProvisioner(+ accounts=account_domain.accounts,+ workspaces=account_domain.provisioning,+ installation=installation,+ telemetry=Telemetry(),+ )+ with pytest.raises(ValueError, match="Setup failed"):+ provisioner.provision(+ SetupInput(email="[email protected]", name="A", password="Valid123!", ip_address="127.0.0.1", language="en-US")+ )+ assert sqlite_session.scalar(select(Account.id)) is None+ assert sqlite_session.scalar(select(Tenant.id)) is None+ assert sqlite_session.scalar(select(DifySetup.version)) is None+++def test_setup_persists_initialized_owner_before_telemetry(+ account_domain: AccountDomain, sqlite_session_factory: sessionmaker[Session]+) -> None:+ reported: list[str] = []++ class Telemetry:+ def report(self) -> None:+ with sqlite_session_factory() as session:+ account = session.scalar(select(Account))+ assert account is not None+ assert account.initialized_at == datetime(2026, 1, 1)+ assert session.scalar(select(DifySetup.version)) is not None+ owner = session.scalar(select(TenantAccountJoin))+ assert owner is not None+ assert owner.account_id == account.id+ assert owner.role == TenantAccountRole.OWNER+ reported.append(account.id)++ account_domain.policy.is_registration_allowed.return_value = False+ account_domain.policy.is_workspace_creation_allowed.return_value = False+ provisioner = AccountSetupProvisioner(+ accounts=account_domain.accounts,+ workspaces=account_domain.provisioning,+ installation=InstallationStateRepository(session_factory=sqlite_session_factory),+ telemetry=Telemetry(),+ )+ provisioner.provision(+ SetupInput(email="[email protected]", name="A", password="Valid123!", ip_address="127.0.0.1", language="en-US")+ )+ assert len(reported) == 1diff --git a/api/tests/unit_tests/services/agent/test_workflow_package_service.py b/api/tests/unit_tests/services/agent/test_workflow_package_service.pyindex 14e884f6d9a..79cd06f1fe1 100644--- a/api/tests/unit_tests/services/agent/test_workflow_package_service.py+++ b/api/tests/unit_tests/services/agent/test_workflow_package_service.py@@ -38,7 +38,7 @@ from services.agent.package_resource_importer import AgentPackageResourceImportefrom services.app_dsl_service import AppDslService, Importfrom services.app_package_service import AppPackageManifest, AppPackageServicefrom services.entities.dsl_entities import ImportStatus-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.plugin.dependencies_analysis import DependenciesAnalysisServicefrom tests.unit_tests.model_factories import make_account, make_app, make_tenant, make_upload_file, make_workflowdiff --git a/api/tests/unit_tests/services/dataset_service_test_helpers.py b/api/tests/unit_tests/services/dataset_service_test_helpers.pyindex 6b554f85bb8..07364ea972c 100644--- a/api/tests/unit_tests/services/dataset_service_test_helpers.py+++ b/api/tests/unit_tests/services/dataset_service_test_helpers.py@@ -44,7 +44,7 @@ from services.entities.knowledge_entities.rag_pipeline_entities import (from services.entities.knowledge_entities.rag_pipeline_entities import (RetrievalSetting as RagPipelineRetrievalSetting,)-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.errors.chunk import ChildChunkDeleteIndexError, ChildChunkIndexingErrorfrom services.errors.dataset import DatasetNameDuplicateErrorfrom services.errors.document import DocumentIndexingErrordiff --git a/api/tests/unit_tests/services/knowledge/test_api_key_service.py b/api/tests/unit_tests/services/knowledge/test_api_key_service.pyindex ce844001ffe..355de55ef51 100644--- a/api/tests/unit_tests/services/knowledge/test_api_key_service.py+++ b/api/tests/unit_tests/services/knowledge/test_api_key_service.py@@ -14,10 +14,10 @@ from models.account import Tenant, TenantAccountJoin, TenantAccountRolefrom models.dataset import Dataset, DatasetPermissionfrom models.enums import PermissionEnumfrom models.model import ApiToken-from repositories.workspace_member_query_repository import WorkspaceMemberQueryRepository+from repositories.workspace.workspace_repository import WorkspaceRepositoryfrom services.api_token_service import ApiTokenCachefrom services.auth.api_key_contracts import ApiKeyNotFoundError-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.knowledge.api_key_service import DatasetApiKeyService@@ -40,7 +40,7 @@ def service(sqlite_session.commit()dataset_access = build_dataset_dependencies(database_client=sqlite_session_factory,- workspace_roles=WorkspaceMemberQueryRepository(session_factory=sqlite_session_factory),+ workspace_roles=WorkspaceRepository(session_factory=sqlite_session_factory),).accessreturn build_dataset_api_key_service(database_client=sqlite_session_factory,diff --git a/api/tests/unit_tests/services/knowledge/test_segment_adapters.py b/api/tests/unit_tests/services/knowledge/test_segment_adapters.pyindex a3cac9fa35e..8f15766dc6f 100644--- a/api/tests/unit_tests/services/knowledge/test_segment_adapters.py+++ b/api/tests/unit_tests/services/knowledge/test_segment_adapters.py@@ -33,7 +33,7 @@ from models.model import UploadFilefrom repositories.knowledge.dataset_repository import SQLAlchemyDatasetRepositoryfrom repositories.knowledge.segment_repository import SQLAlchemySegmentRepositoryfrom repositories.knowledge.upload_file_repository import SQLAlchemyKnowledgeUploadRepository-from repositories.workspace_member_query_repository import WorkspaceMemberQueryRepository+from repositories.workspace.workspace_repository import WorkspaceRepositoryfrom services.knowledge.dataset_access import DatasetAccessServicefrom services.knowledge.dataset_service import SegmentServicefrom services.knowledge.entities.segments import ChildChunkUpdateArgs, SegmentUpdateArgs@@ -273,7 +273,7 @@ def _application(return DatasetSegmentApplicationService(dataset_access=DatasetAccessService(datasets=datasets,- workspace_roles=WorkspaceMemberQueryRepository(session_factory=factory),+ workspace_roles=WorkspaceRepository(session_factory=factory),legacy_permissions_enabled=False,),scopes=datasets,diff --git a/api/tests/unit_tests/services/test_account_activation_service.py b/api/tests/unit_tests/services/test_account_activation_service.pyindex 43a67f59651..bd3bd4d39d7 100644--- a/api/tests/unit_tests/services/test_account_activation_service.py+++ b/api/tests/unit_tests/services/test_account_activation_service.py@@ -6,15 +6,13 @@ from services.account_activation_service import (AccountActivationEligibility,AccountActivationRepository,AccountActivationService,- EmailDomainSuspendedError,- FrozenAccountError,- InvalidInvitationError,- InvitationAccountMismatchError,InvitationTokenStore,WorkspaceInvitePolicy,WorkspaceMemberAccessSync,WorkspaceMembershipCache,)+from services.account_errors import AccountEmailDomainSuspendedError as EmailDomainSuspendedError+from services.account_errors import FrozenAccountError, InvalidInvitationError, InvitationAccountMismatchErrorfrom services.entities.account_activation_entities import (AccountInvitation,AccountSetup,diff --git a/api/tests/unit_tests/services/test_account_email_registration_adapters.py b/api/tests/unit_tests/services/test_account_email_registration_adapters.pydeleted file mode 100644index 14d2fd725f2..00000000000--- a/api/tests/unit_tests/services/test_account_email_registration_adapters.py+++ /dev/null@@ -1,176 +0,0 @@-from unittest.mock import Mock, patch--import pytest-from sqlalchemy.orm import Session, sessionmaker--from extensions.ext_redis import RedisClientWrapper-from models.account import Account-from services.account_email_registration_adapters import (- AccountServiceRegistrationGateway,- BillingAccountRegistrationPolicyGateway,- RedisEmailRegistrationSecurityGateway,- TokenManagerEmailRegistrationTokenGateway,-)-from services.account_errors import (- AccountEmailDomainSuspendedError,- AccountNormalizedEmailAlreadyInUseError,- EmailRegistrationSeatsLimitError,-)-from services.account_service import TokenPair-from services.entities.account_entities import AccountEmailRegistrationPhase, AccountEmailRegistrationToken-from services.errors.account import (- AccountNormalizedEmailAlreadyInUseError as AccountNormalizedEmailAlreadyInUseServiceError,-)-from services.errors.account import EmailDomainSuspendedError, SeatsLimitExceededError---def test_token_gateway_rejects_malformed_payload() -> None:- gateway = TokenManagerEmailRegistrationTokenGateway()-- with patch(- "services.account_email_registration_adapters.TokenManager.get_token_data",- return_value={"email": "[email protected]", "phase": "unknown"},- ):- assert gateway.get("token") is None---def test_token_gateway_issues_verified_registration_state() -> None:- gateway = TokenManagerEmailRegistrationTokenGateway()- token_data = AccountEmailRegistrationToken(- email="[email protected]",- code="123456",- phase=AccountEmailRegistrationPhase.REGISTER,- )-- with patch(- "services.account_email_registration_adapters.TokenManager.generate_token",- return_value="token",- ) as generate_token:- assert gateway.issue(token_data) == "token"-- generate_token.assert_called_once_with(- email="[email protected]",- token_type="email_register",- additional_data={"code": "123456", "phase": "register"},- )---def test_security_gateway_delegates_ip_limit_to_existing_policy_owner() -> None:- redis = Mock(spec=RedisClientWrapper)- gateway = RedisEmailRegistrationSecurityGateway(- redis=redis,- verification_failure_limit=5,- verification_lockout_duration=600,- )-- with patch(- "services.account_email_registration_adapters.AccountService.is_email_send_ip_limit",- return_value=False,- ) as is_email_send_ip_limit:- assert gateway.is_ip_limited("127.0.0.1") is False-- is_email_send_ip_limit.assert_called_once_with("127.0.0.1")- redis.get.assert_not_called()---def test_security_gateway_uses_registration_and_login_keys() -> None:- redis = Mock(spec=RedisClientWrapper)- redis.get.return_value = 1- gateway = RedisEmailRegistrationSecurityGateway(- redis=redis,- verification_failure_limit=5,- verification_lockout_duration=600,- )-- with patch(- "services.account_email_registration_adapters.AccountService.reset_login_error_rate_limit"- ) as reset_login_error_rate_limit:- gateway.record_verification_failure("[email protected]")- gateway.reset_verification_failures("[email protected]")- gateway.reset_login_failures("[email protected]")-- redis.setex.assert_called_once_with("email_register_error_rate_limit:[email protected]", 600, 2)- redis.delete.assert_called_once_with("email_register_error_rate_limit:[email protected]")- reset_login_error_rate_limit.assert_called_once_with("[email protected]")---def test_billing_policy_is_disabled_outside_cloud() -> None:- gateway = BillingAccountRegistrationPolicyGateway(enabled=False)-- with patch("services.account_email_registration_adapters.BillingService.get_email_freeze_type") as freeze_type:- assert gateway.get_freeze_type("[email protected]") is None-- freeze_type.assert_not_called()--- ("service_error", "application_error"),- [- pytest.param(SeatsLimitExceededError(), EmailRegistrationSeatsLimitError, id="seat-limit"),- pytest.param(EmailDomainSuspendedError(), AccountEmailDomainSuspendedError, id="suspended-domain"),- pytest.param(- AccountNormalizedEmailAlreadyInUseServiceError(),- AccountNormalizedEmailAlreadyInUseError,- id="normalized-email-in-use",- ),- ],-)-def test_registration_gateway_translates_account_provisioning_errors(- sqlite_session_factory: sessionmaker[Session],- service_error: Exception,- application_error: type[Exception],-) -> None:- gateway = AccountServiceRegistrationGateway(session_factory=sqlite_session_factory)-- with patch(- "services.account_email_registration_adapters.AccountService.create_account_and_tenant",- side_effect=service_error,- ):- with pytest.raises(application_error):- gateway.create(- email="[email protected]",- password="ValidPass123!",- interface_language="en-US",- timezone=None,- ip_address="127.0.0.1",- )---def test_registration_gateway_owns_short_lived_sessions(- sqlite_session: Session,- sqlite_session_factory: sessionmaker[Session],-) -> None:- gateway = AccountServiceRegistrationGateway(session_factory=sqlite_session_factory)-- def create_account(*, session: Session, **_: object) -> Account:- account = Account(name="[email protected]", email="[email protected]")- account.id = "account-1"- session.add(account)- session.commit()- return account-- with patch(- "services.account_email_registration_adapters.AccountService.create_account_and_tenant",- side_effect=create_account,- ) as create_account_and_tenant:- account_id = gateway.create(- email="[email protected]",- password="ValidPass123!",- interface_language="en-US",- timezone=None,- ip_address="127.0.0.1",- )-- assert create_account_and_tenant.call_args.kwargs["check_normalized_email"] is True- sqlite_session.expire_all()- assert sqlite_session.get(Account, account_id) is not None-- with patch(- "services.account_email_registration_adapters.AccountService.login",- return_value=TokenPair(access_token="access", refresh_token="refresh", csrf_token="csrf"),- ) as login:- tokens = gateway.login(account_id, ip_address="127.0.0.1")-- assert tokens.access_token == "access"- assert login.call_args.kwargs["account"].id == account_id- assert isinstance(login.call_args.kwargs["session"], Session)diff --git a/api/tests/unit_tests/services/test_account_security_gateway.py b/api/tests/unit_tests/services/test_account_security_gateway.pyindex 077210e5af9..ef5be1fd638 100644--- a/api/tests/unit_tests/services/test_account_security_gateway.py+++ b/api/tests/unit_tests/services/test_account_security_gateway.py@@ -2,6 +2,7 @@import loggingfrom typing import cast+from unittest.mock import Mock, callimport pytestfrom redis import RedisError@@ -45,3 +46,38 @@ def test_redis_failures_remain_fail_open_but_are_logged("Redis unavailable while recording an account email verification failure","Redis unavailable while resetting account email verification failures",]++[email protected]("already_frozen", [True, False], ids=["frozen-ip", "lost-hour-counter-race"])+def test_frozen_ip_and_concurrent_hour_claim_remain_limited(already_frozen: bool) -> None:+ redis = Mock(spec=RedisClientWrapper)+ values = (+ {"email_send_ip_limit_freeze:127.0.0.1": b"1"}+ if already_frozen+ else {"email_send_ip_limit_minute:127.0.0.1": b"4"}+ )+ redis.get.side_effect = values.get+ redis.set.return_value = False+ gateway = RedisAccountEmailSecurityGateway(+ redis=redis,+ email_send_ip_limit_per_minute=3,+ verification_failure_limit=5,+ verification_lockout_duration=3600,+ verification_key_prefix="forgot_password_error_rate_limit",+ )++ assert gateway.is_ip_limited("127.0.0.1") is True++ if already_frozen:+ redis.get.assert_called_once_with("email_send_ip_limit_freeze:127.0.0.1")+ redis.set.assert_not_called()+ redis.setex.assert_not_called()+ else:+ assert redis.get.call_args_list == [+ call("email_send_ip_limit_freeze:127.0.0.1"),+ call("email_send_ip_limit_minute:127.0.0.1"),+ call("email_send_ip_limit_hour:127.0.0.1"),+ ]+ redis.set.assert_called_once_with("email_send_ip_limit_hour:127.0.0.1", 1, ex=600, nx=True)+ redis.setex.assert_called_once_with("email_send_ip_limit_freeze:127.0.0.1", 3600, 1)+ redis.expire.assert_not_called()diff --git a/api/tests/unit_tests/services/test_account_service.py b/api/tests/unit_tests/services/test_account_service.pydeleted file mode 100644index 02165eae94b..00000000000--- a/api/tests/unit_tests/services/test_account_service.py+++ /dev/null@@ -1,3108 +0,0 @@-import json-from collections.abc import Callable, Iterator, Sequence-from datetime import datetime, timedelta-from unittest.mock import MagicMock, patch-from uuid import UUID--import pytest-from sqlalchemy import event, select-from sqlalchemy.engine import Connection-from sqlalchemy.engine.interfaces import DBAPICursor, ExecutionContext-from sqlalchemy.orm import Session, sessionmaker--from enums import DeploymentEdition-from models.account import (- Account,- AccountStatus,- Tenant,- TenantAccountJoin,- TenantAccountRole,- TenantStatus,-)-from models.model import DifySetup-from services.account_email import normalize_email-from services.account_service import (- AccountService,- EnterpriseWorkspaceMemberAccountNotFoundError,- EnterpriseWorkspaceMemberWorkspaceNotFoundError,- RegisterService,- TenantService,-)-from services.enterprise.rbac_service import MemberRolesResponse, MembersInRole, Paginated, RBACRole-from services.errors.account import (- AccountAlreadyInTenantError,- AccountEmailAlreadyInUseError,- AccountNotFoundError,- AccountRegisterError,- EmailDomainSuspendedError,- NoPermissionError,-)-from tests.unit_tests.config_override import config_overrides_context-from tests.unit_tests.model_factories import make_tenant--type _MockDependencies = dict[str, MagicMock]---class TestAccountAssociatedDataFactory:- """Factory class for creating test data and mock objects for account service tests."""-- @staticmethod- def create_account_mock(- account_id: str = "user-123",- email: str = "[email protected]",- name: str = "Test User",- status: AccountStatus | str = AccountStatus.ACTIVE,- password: str = "hashed_password",- password_salt: str = "salt",- interface_language: str = "en-US",- interface_theme: str = "light",- timezone: str = "UTC",- ) -> Account:- """Create an account with specified attributes."""- account = Account(- name=name,- email=email,- password=password,- password_salt=password_salt,- interface_language=interface_language,- interface_theme=interface_theme,- timezone=timezone,- status=AccountStatus(status),- initialized_at=None,- )- account.id = account_id- # Set last_active_at to a datetime object that's older than 10 minutes- account.last_active_at = datetime.now() - timedelta(minutes=15)- return account---def _tenant(session: Session | None = None) -> Tenant:- tenant = make_tenant(tenant_id=None, name="Test Workspace")- if session is not None:- session.add(tenant)- return tenant---class TestAccountService:- @pytest.fixture(autouse=True)- def _account_config(self, config_overrides: Callable[..., None]) -> None:- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)-- """- Comprehensive unit tests for AccountService methods.-- This test suite covers all account-related operations including:- - Account creation and registration- - Password management- - JWT token generation- - User loading and tenant management- - Error conditions and edge cases- """-- @pytest.fixture- def mock_password_dependencies(self) -> Iterator[_MockDependencies]:- """Mock setup for password-related functions."""- with (- patch("services.account_service.hash_password") as mock_hash_password,- patch("services.account_service.valid_password") as mock_valid_password,- ):- yield {- "hash_password": mock_hash_password,- "valid_password": mock_valid_password,- }-- @pytest.fixture- def mock_external_service_dependencies(self) -> Iterator[_MockDependencies]:- """Mock setup for external service dependencies."""- with (- 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,- ):- yield {- "feature_service": mock_feature_service,- "billing_service": mock_billing_service,- "passport_service": mock_passport_service,- }-- # ==================== Account Creation Tests ====================-- def test_create_account_success(- self,- sqlite_session_factory: sessionmaker[Session],- mock_password_dependencies: _MockDependencies,- mock_external_service_dependencies: _MockDependencies,- ) -> None:- """Test successful account creation with all required parameters."""- # 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- mock_password_dependencies["hash_password"].return_value = b"hashed_password"-- # Execute test- with sqlite_session_factory() as service_session:- result = AccountService.create_account(- email="[email protected]",- name="Test User",- interface_language="en-US",- password="password123",- interface_theme="light",- ip_address="203.0.113.10",- session=service_session,- )- account_id = result.id-- assert result.email == "[email protected]"- assert result.normalized_email == "[email protected]"- assert result.name == "Test User"- assert result.interface_language == "en-US"- assert result.interface_theme == "light"- assert result.password is not None- assert result.password_salt is not None- assert result.timezone == "America/New_York"- assert result.last_login_ip == "203.0.113.10"-- with sqlite_session_factory() as assertion_session:- persisted_account = assertion_session.get(Account, account_id)- assert persisted_account is not None- assert persisted_account.email == "[email protected]"- assert persisted_account.normalized_email == "[email protected]"- assert persisted_account.name == "Test User"- assert persisted_account.interface_language == "en-US"- assert persisted_account.interface_theme == "light"- assert persisted_account.password is not None- assert persisted_account.password_salt is not None- assert persisted_account.timezone == "America/New_York"- assert persisted_account.last_login_ip == "203.0.113.10"-- @pytest.mark.parametrize(- ("existing_email", "new_email", "normalized_email"),- [- ],- )- def test_create_account_rejects_normalized_email_only_when_requested(- self,- existing_email: str,- new_email: str,- normalized_email: str,- sqlite_session: Session,- mock_external_service_dependencies: _MockDependencies,- ) -> None:- 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-- sqlite_session.add(- Account(- name="Existing User",- email=existing_email,- normalized_email=normalized_email,- )- )- sqlite_session.commit()-- with pytest.raises(AccountEmailAlreadyInUseError):- AccountService.create_account(- email=new_email,- name="New User",- interface_language="en-US",- check_normalized_email=True,- session=sqlite_session,- )-- duplicate = AccountService.create_account(- email=new_email,- name="New User",- interface_language="en-US",- session=sqlite_session,- )- assert duplicate.normalized_email == normalized_email-- def test_create_account_uses_explicit_timezone(- self,- sqlite_session_factory: sessionmaker[Session],- mock_password_dependencies: _MockDependencies,- mock_external_service_dependencies: _MockDependencies,- ) -> None:- """Test account creation prefers explicit browser timezone."""- 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- mock_password_dependencies["hash_password"].return_value = b"hashed_password"-- with sqlite_session_factory() as service_session:- result = AccountService.create_account(- email="[email protected]",- name="Test User",- interface_language="en-US",- password="password123",- timezone="Asia/Shanghai",- session=service_session,- )- account_id = result.id- assert result.timezone == "Asia/Shanghai"-- with sqlite_session_factory() as assertion_session:- persisted_account = assertion_session.get(Account, account_id)- assert persisted_account is not None- assert persisted_account.timezone == "Asia/Shanghai"-- def test_create_account_registration_disabled(- self, unbound_session: Session, mock_external_service_dependencies: _MockDependencies- ) -> None:- """Test account creation when registration is disabled."""- # Setup mocks- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = False-- # Execute test and verify exception- with pytest.raises(AccountNotFoundError, match="Account registration is disabled"):- AccountService.create_account(- email="[email protected]",- name="Test User",- interface_language="en-US",- session=unbound_session,- )-- def test_create_account_email_frozen(- self,- unbound_session: Session,- mock_external_service_dependencies: _MockDependencies,- config_overrides: Callable[..., None],- ) -> None:- """Test account creation with frozen email address."""- # 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 = True- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)- with pytest.raises(AccountRegisterError):- AccountService.create_account(- email="[email protected]",- name="Test User",- interface_language="en-US",- session=unbound_session,- )-- def test_create_account_suspended_email_domain(- self, unbound_session: Session, mock_external_service_dependencies: _MockDependencies- ) -> None:- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- 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.create_account(- email="[email protected]",- name="Test User",- interface_language="en-US",- session=unbound_session,- )-- def test_create_account_without_password(- self,- sqlite_session_factory: sessionmaker[Session],- mock_external_service_dependencies: _MockDependencies,- ) -> None:- """Test account creation without password (for invite-based registration)."""- # 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-- # Execute test- with sqlite_session_factory() as service_session:- result = AccountService.create_account(- email="[email protected]",- name="Test User",- interface_language="zh-CN",- password=None,- interface_theme="dark",- session=service_session,- )- account_id = result.id-- assert result.email == "[email protected]"- assert result.name == "Test User"- assert result.interface_language == "zh-CN"- assert result.interface_theme == "dark"- assert result.password is None- assert result.password_salt is None- assert result.timezone is not None- assert result.last_login_ip is None-- with sqlite_session_factory() as assertion_session:- persisted_account = assertion_session.get(Account, account_id)- assert persisted_account is not None- assert persisted_account.email == "[email protected]"- assert persisted_account.name == "Test User"- assert persisted_account.interface_language == "zh-CN"- assert persisted_account.interface_theme == "dark"- assert persisted_account.password is None- assert persisted_account.password_salt is None- assert persisted_account.timezone is not None- assert persisted_account.last_login_ip is None-- def test_update_login_info_overwrites_initial_registration_ip(- self,- sqlite_session_factory: sessionmaker[Session],- mock_external_service_dependencies: _MockDependencies,- ) -> None:- 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-- with sqlite_session_factory() as service_session:- account = AccountService.create_account(- email="[email protected]",- name="Test User",- interface_language="en-US",- ip_address="203.0.113.10",- session=service_session,- )- account_id = account.id-- AccountService.update_login_info(account, service_session, ip_address="203.0.113.11")-- with sqlite_session_factory() as assertion_session:- persisted_account = assertion_session.get(Account, account_id)- assert persisted_account is not None- assert persisted_account.last_login_ip == "203.0.113.11"- assert persisted_account.last_login_at is not None-- # ==================== User Loading Tests ====================-- def test_load_user_success(self, sqlite_session: Session) -> None:- """Test successful user loading with current tenant."""- account = Account(name="Test User", email="[email protected]")- tenant = Tenant(name="Test Workspace")- sqlite_session.add_all([account, tenant])- sqlite_session.flush()- tenant_join = TenantAccountJoin(- tenant_id=tenant.id,- account_id=account.id,- role=TenantAccountRole.NORMAL,- current=True,- )- sqlite_session.add(tenant_join)- sqlite_session.commit()-- with patch.object(AccountService, "_refresh_account_last_active") as mock_refresh_last_active:- result = AccountService.load_user(account.id, sqlite_session)-- assert result is account- assert result.current_tenant_id == tenant.id- assert result.current_role == TenantAccountRole.NORMAL- mock_refresh_last_active.assert_called_once_with(account, sqlite_session)-- def test_load_user_not_found(self, sqlite_session: Session) -> None:- """Test user loading when user does not exist."""- result = AccountService.load_user("non-existent-user", sqlite_session)-- assert result is None-- def test_load_user_banned(self, sqlite_session: Session) -> None:- """Test user loading when user is banned."""- from werkzeug.exceptions import Unauthorized-- account = Account(name="Banned User", email="[email protected]", status=AccountStatus.BANNED)- sqlite_session.add(account)- sqlite_session.commit()-- with pytest.raises(Unauthorized):- AccountService.load_user(account.id, sqlite_session)-- def test_load_user_no_current_tenant(self, sqlite_session_factory: sessionmaker[Session]) -> None:- """Test user loading when user has no current tenant but has available tenants."""- with sqlite_session_factory() as service_session:- account = Account(name="Test User", email="[email protected]")- tenant = Tenant(name="Test Workspace")- service_session.add_all([account, tenant])- service_session.flush()- available_tenant_join = TenantAccountJoin(- tenant_id=tenant.id,- account_id=account.id,- role=TenantAccountRole.NORMAL,- current=False,- )- service_session.add(available_tenant_join)- service_session.commit()- account_id = account.id- tenant_id = tenant.id- tenant_join_id = available_tenant_join.id-- mock_now = datetime(2026, 6, 5, 11, 0, 0)- with (- patch.object(Account, "set_tenant_id_with_session") as mock_set_tenant_id,- patch("services.account_service.naive_utc_now", return_value=mock_now),- patch.object(AccountService, "_refresh_account_last_active") as mock_refresh_last_active,- ):- result = AccountService.load_user(account_id, service_session)- assert result is not None- mock_set_tenant_id.assert_called_once_with(tenant_id, session=service_session)- mock_refresh_last_active.assert_called_once_with(result, service_session)-- with sqlite_session_factory() as assertion_session:- persisted_tenant_join = assertion_session.get(TenantAccountJoin, tenant_join_id)- assert persisted_tenant_join is not None- assert persisted_tenant_join.current is True- assert persisted_tenant_join.last_opened_at == mock_now-- def test_load_user_switches_from_archived_current_tenant(self, sqlite_session: Session) -> None:- account = Account(name="Test User", email="[email protected]")- archived_tenant = Tenant(name="Archived Workspace", status=TenantStatus.ARCHIVE)- available_tenant = Tenant(name="Available Workspace")- sqlite_session.add_all([account, archived_tenant, available_tenant])- sqlite_session.flush()- archived_join = TenantAccountJoin(- tenant_id=archived_tenant.id,- account_id=account.id,- role=TenantAccountRole.NORMAL,- current=True,- )- available_join = TenantAccountJoin(- tenant_id=available_tenant.id,- account_id=account.id,- role=TenantAccountRole.NORMAL,- current=False,- )- sqlite_session.add_all([archived_join, available_join])- sqlite_session.commit()-- with patch.object(AccountService, "_refresh_account_last_active"):- result = AccountService.load_user(account.id, sqlite_session)-- assert result is account- assert result.current_tenant_id == available_tenant.id- assert archived_join.current is False- assert available_join.current is True-- def test_load_user_returns_none_without_normal_tenant(self, sqlite_session: Session) -> None:- account = Account(name="Test User", email="[email protected]")- archived_tenant = Tenant(name="Archived Workspace", status=TenantStatus.ARCHIVE)- sqlite_session.add_all([account, archived_tenant])- sqlite_session.flush()- archived_join = TenantAccountJoin(- tenant_id=archived_tenant.id,- account_id=account.id,- role=TenantAccountRole.NORMAL,- current=True,- )- sqlite_session.add(archived_join)- sqlite_session.commit()-- result = AccountService.load_user(account.id, sqlite_session)-- assert result is None- assert archived_join.current is False-- def test_load_user_keeps_tenant_accessible_with_expiring_session(self, sqlite_session: Session) -> None:- account = Account(name="Test User", email="[email protected]")- tenant = Tenant(name="Test Workspace")- sqlite_session.add_all([account, tenant])- sqlite_session.flush()- sqlite_session.add(- TenantAccountJoin(- tenant_id=tenant.id,- account_id=account.id,- role=TenantAccountRole.NORMAL,- current=False,- )- )- sqlite_session.commit()- account_id = account.id- tenant_id = tenant.id-- with Session(sqlite_session.get_bind()) as expiring_session:- with patch.object(AccountService, "_refresh_account_last_active"):- result = AccountService.load_user(account_id, expiring_session)-- assert result is not None- assert result.current_tenant_id == tenant_id-- def test_load_user_no_tenants(self, sqlite_session: Session) -> None:- """Test user loading when user has no tenants at all."""- account = Account(name="Test User", email="[email protected]")- sqlite_session.add(account)- sqlite_session.commit()-- result = AccountService.load_user(account.id, sqlite_session)-- assert result is None-- def test_refresh_account_last_active_uses_redis_gate_and_conditional_update(- self, sqlite_session_factory: sessionmaker[Session]- ) -> None:- """Test last-active refresh is gated in Redis and conditionally written to DB."""- now = datetime(2026, 6, 2, 2, 45, 49)- with sqlite_session_factory() as service_session:- account = Account(name="Test User", email="[email protected]")- account.last_active_at = now - timedelta(minutes=15)- service_session.add(account)- service_session.commit()- account_id = account.id-- with (- patch("services.account_service.naive_utc_now", return_value=now),- patch("services.account_service.redis_client") as mock_redis_client,- ):- mock_redis_client.set.return_value = True-- AccountService._refresh_account_last_active(account, service_session)-- mock_redis_client.set.assert_called_once_with(- f"account_last_active_refresh:{account_id}",- 1,- ex=600,- nx=True,- )- with sqlite_session_factory() as assertion_session:- persisted_account = assertion_session.get(Account, account_id)- assert persisted_account is not None- assert persisted_account.last_active_at == now-- def test_refresh_account_last_active_skips_db_when_redis_gate_exists(- self, sqlite_session_factory: sessionmaker[Session]- ) -> None:- """Test concurrent refresh attempts do not enqueue duplicate DB updates."""- now = datetime(2026, 6, 2, 2, 45, 49)- original_last_active_at = now - timedelta(minutes=15)- with sqlite_session_factory() as service_session:- account = Account(name="Test User", email="[email protected]")- account.last_active_at = original_last_active_at- service_session.add(account)- service_session.commit()- account_id = account.id-- with (- patch("services.account_service.naive_utc_now", return_value=now),- patch("services.account_service.redis_client") as mock_redis_client,- ):- mock_redis_client.set.return_value = None-- AccountService._refresh_account_last_active(account, service_session)-- mock_redis_client.set.assert_called_once_with(- f"account_last_active_refresh:{account_id}",- 1,- ex=600,- nx=True,- )- with sqlite_session_factory() as assertion_session:- persisted_account = assertion_session.get(Account, account_id)- assert persisted_account is not None- assert persisted_account.last_active_at == original_last_active_at-- def test_refresh_account_last_active_skips_recent_account(- self, sqlite_session_factory: sessionmaker[Session]- ) -> None:- """Test recent activity does not touch Redis or DB."""- now = datetime(2026, 6, 2, 2, 45, 49)- original_last_active_at = now - timedelta(minutes=5)- with sqlite_session_factory() as service_session:- account = Account(name="Test User", email="[email protected]")- account.last_active_at = original_last_active_at- service_session.add(account)- service_session.commit()- account_id = account.id-- with (- patch("services.account_service.naive_utc_now", return_value=now),- patch("services.account_service.redis_client") as mock_redis_client,- ):- AccountService._refresh_account_last_active(account, service_session)-- mock_redis_client.set.assert_not_called()- with sqlite_session_factory() as assertion_session:- persisted_account = assertion_session.get(Account, account_id)- assert persisted_account is not None- assert persisted_account.last_active_at == original_last_active_at---class TestTenantService:- @pytest.fixture(autouse=True)- def _tenant_config(self, config_overrides: Callable[..., None]) -> None:- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY, RBAC_ENABLED=False)-- """- Comprehensive unit tests for TenantService methods.-- This test suite covers all tenant-related operations including:- - Tenant creation and management- - Member management and permissions- - Tenant switching- - Role updates and permission checks- - Error conditions and edge cases- """-- @pytest.fixture- def mock_rsa_dependencies(self) -> Iterator[MagicMock]:- """Mock setup for RSA-related functions."""- with patch("services.account_service.generate_key_pair") as mock_generate_key_pair:- yield mock_generate_key_pair-- @pytest.fixture- def mock_external_service_dependencies(self) -> Iterator[_MockDependencies]:- """Mock setup for external service dependencies."""- with (- patch("services.account_service.SystemFeatureService") as mock_feature_service,- patch("services.account_service.BillingService") as mock_billing_service,- ):- yield {- "feature_service": mock_feature_service,- "billing_service": mock_billing_service,- }-- def _add_tenant_account_join(- self,- sqlite_session: Session,- tenant: Tenant,- account_id: str,- role: TenantAccountRole,- *,- current: bool = False,- ) -> TenantAccountJoin:- """Create a real membership row for TenantService persistence tests."""- tenant_account_join = TenantAccountJoin(- tenant_id=tenant.id,- account_id=account_id,- role=role,- current=current,- )- sqlite_session.add(tenant_account_join)- return tenant_account_join-- def _db_role_of(self, sqlite_session: Session, tenant: Tenant, account_id: str) -> str | None:- return sqlite_session.scalar(- select(TenantAccountJoin.role).where(- TenantAccountJoin.tenant_id == tenant.id,- TenantAccountJoin.account_id == account_id,- )- )-- def test_iter_member_account_id_batches_uses_offset_limit(self, sqlite_session: Session) -> None:- tenant_id = "00000000-0000-0000-0000-000000000001"- account_ids = [- "00000000-0000-0000-0000-000000000011",- "00000000-0000-0000-0000-000000000012",- "00000000-0000-0000-0000-000000000013",- ]- joins = [- TenantAccountJoin(- tenant_id=tenant_id,- account_id=account_id,- role=TenantAccountRole.NORMAL,- current=False,- )- for account_id in account_ids- ]- for index, join in enumerate(joins, start=21):- join.id = f"00000000-0000-0000-0000-{index:012d}"- sqlite_session.add_all(joins)- sqlite_session.commit()-- pagination_parameters: list[tuple[int, int]] = []-- def record_sql(- _conn: Connection,- _cursor: DBAPICursor,- statement: str,- parameters: Sequence[object],- _context: ExecutionContext | None,- _executemany: bool,- ) -> None:- if "FROM tenant_account_joins" in statement:- limit, offset = parameters[-2:]- assert isinstance(limit, int)- assert isinstance(offset, int)- pagination_parameters.append((limit, offset))-- bind = sqlite_session.get_bind()- event.listen(bind, "before_cursor_execute", record_sql)- try:- batches = list(TenantService.iter_member_account_id_batches(tenant_id, 2, session=sqlite_session))- finally:- event.remove(bind, "before_cursor_execute", record_sql)-- assert batches == [account_ids[:2], account_ids[2:]]- assert pagination_parameters == [(2, 0), (2, 2), (2, 4)]-- # ==================== get_account_role_in_tenant Tests ====================- # Backs the auth pipeline's `load_workspace_role`: None => non-member- # (pipeline maps to 404), otherwise the caller's role (out-of-set role => 403).-- def test_get_account_role_in_tenant_returns_role_for_member(self, sqlite_session: Session) -> None:- """A row in TenantAccountJoin yields the caller's role."""- sqlite_session.add(- TenantAccountJoin(tenant_id="tenant-1", account_id="account-1", role=TenantAccountRole.ADMIN)- )- sqlite_session.commit()-- role = TenantService.get_account_role_in_tenant("account-1", "tenant-1", session=sqlite_session)-- assert role == TenantAccountRole.ADMIN-- def test_get_account_role_in_tenant_returns_none_for_non_member(self, sqlite_session: Session) -> None:- """No join row => None, so the gate cannot leak the workspace's existence."""- role = TenantService.get_account_role_in_tenant("account-1", "tenant-1", session=sqlite_session)-- assert role is None-- def test_get_account_role_in_tenant_short_circuits_empty_account_id(self, unbound_session: Session) -> None:- """None/empty account_id (SSO bearer, missing identity) returns None- without ever touching the session."""- assert TenantService.get_account_role_in_tenant(None, "tenant-1", session=unbound_session) is None-- def test_get_account_role_in_tenant_query_is_scoped(self, sqlite_session: Session) -> None:- """The lookup must filter on BOTH tenant_id and account_id."""- account_id = "11111111-1111-1111-1111-111111111111"- tenant_id = "22222222-2222-2222-2222-222222222222"- sqlite_session.add_all(- [- TenantAccountJoin(tenant_id=tenant_id, account_id=account_id, role=TenantAccountRole.NORMAL),- TenantAccountJoin(tenant_id="other-tenant", account_id=account_id, role=TenantAccountRole.ADMIN),- TenantAccountJoin(tenant_id=tenant_id, account_id="other-account", role=TenantAccountRole.OWNER),- ]- )- sqlite_session.commit()-- assert (- TenantService.get_account_role_in_tenant(account_id, tenant_id, session=sqlite_session)- == TenantAccountRole.NORMAL- )- assert TenantService.get_account_role_in_tenant(account_id, "missing-tenant", session=sqlite_session) is None- assert TenantService.get_account_role_in_tenant("missing-account", tenant_id, session=sqlite_session) is None-- # ==================== Tenant Creation Tests ====================-- def test_create_owner_tenant_if_not_exist_new_user(- self,- sqlite_session_factory: sessionmaker[Session],- mock_rsa_dependencies: MagicMock,- mock_external_service_dependencies: _MockDependencies,- ) -> None:- """Creating an owner workspace persists both the tenant and owner membership."""- mock_account = TestAccountAssociatedDataFactory.create_account_mock()-- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True- mock_external_service_dependencies[- "feature_service"- ].get_license.return_value.workspaces.is_available.return_value = True- mock_rsa_dependencies.return_value = "mock_public_key"-- with (- patch("services.credit_pool_service.CreditPoolService.create_default_pool"),- patch("services.account_service.tenant_was_created.send") as mock_tenant_was_created,- ):- with sqlite_session_factory() as service_session:- TenantService.create_owner_tenant_if_not_exist(mock_account, session=service_session)- tenant = service_session.scalar(select(Tenant).where(Tenant.name == "Test User's Workspace"))- assert tenant is not None- tenant_id = tenant.id- assert mock_account.current_tenant_id == tenant.id- mock_tenant_was_created.assert_called_once_with(tenant)-- mock_rsa_dependencies.assert_called_once_with(tenant_id)-- with sqlite_session_factory() as assertion_session:- tenant = assertion_session.get(Tenant, tenant_id)- assert tenant is not None- assert tenant.encrypt_public_key == "mock_public_key"-- tenant_account_join = assertion_session.scalar(- select(TenantAccountJoin).where(- TenantAccountJoin.tenant_id == tenant_id,- TenantAccountJoin.account_id == "user-123",- )- )- assert tenant_account_join is not None- assert tenant_account_join.role == TenantAccountRole.OWNER-- # ==================== Member Management Tests ====================-- def test_create_tenant_member_success(self, sqlite_session_factory: sessionmaker[Session]) -> None:- """Creating a member persists and returns the tenant/account join row."""- with sqlite_session_factory() as service_session:- tenant = Tenant(name="Test Workspace")- account = Account(name="Test User", email="[email protected]")- service_session.add_all([tenant, account])- service_session.flush()- tenant_id = tenant.id- account_id = account.id- service_session.commit()-- result = TenantService.create_tenant_member(tenant, account, service_session, "normal")- tenant_account_join_id = result.id-- with sqlite_session_factory() as assertion_session:- persisted_tenant_account_join = assertion_session.get(- TenantAccountJoin,- tenant_account_join_id,- )- assert persisted_tenant_account_join is not None- assert persisted_tenant_account_join.tenant_id == tenant_id- assert persisted_tenant_account_join.account_id == account_id- assert persisted_tenant_account_join.role == TenantAccountRole.NORMAL-- def test_create_tenant_member_queues_joined_member_rbac_sync(- self,- sqlite_session_factory: sessionmaker[Session],- ) -> None:- """New regular members are synced into auto-included RBAC resource whitelists."""- import tasks.initialize_created_app_rbac_access_task as rbac_task_module-- delay = MagicMock()- with sqlite_session_factory() as service_session:- tenant = Tenant(name="Test Workspace")- account = Account(name="Test User", email="[email protected]")- service_session.add_all([tenant, account])- service_session.flush()- tenant_id = tenant.id- account_id = account.id- service_session.commit()-- with (- config_overrides_context(RBAC_ENABLED=True),- patch.object(rbac_task_module.sync_joined_workspace_member_rbac_access_task, "delay", delay),- ):- TenantService.create_tenant_member(- tenant,- account,- service_session,- "normal",- operator_account_id="operator-1",- )-- delay.assert_called_once_with(- tenant_id,- account_id,- operator_account_id="operator-1",- )-- def test_create_tenant_member_does_not_queue_pending_member_rbac_sync(- self,- sqlite_session_factory: sessionmaker[Session],- ) -> None:- """Pending invited members are synced after activation, not at invitation time."""- import tasks.initialize_created_app_rbac_access_task as rbac_task_module-- delay = MagicMock()- with sqlite_session_factory() as service_session:- tenant = Tenant(name="Test Workspace")- account = Account(name="Test User", email="[email protected]", status=AccountStatus.PENDING)- service_session.add_all([tenant, account])- service_session.flush()- service_session.commit()-- with (- config_overrides_context(RBAC_ENABLED=True),- patch.object(rbac_task_module.sync_joined_workspace_member_rbac_access_task, "delay", delay),- ):- TenantService.create_tenant_member(- tenant,- account,- service_session,- "normal",- operator_account_id="operator-1",- )-- delay.assert_not_called()-- def test_join_enterprise_workspace_member_success(self, sqlite_session_factory: sessionmaker[Session]) -> None:- with sqlite_session_factory() as service_session:- tenant = Tenant(name="Test Workspace", status=TenantStatus.NORMAL)- account = Account(name="Test User", email="[email protected]")- service_session.add_all([tenant, account])- service_session.flush()- tenant_id = tenant.id- account_id = account.id- service_session.commit()-- with patch("services.account_service.TenantService.create_tenant_member") as create_tenant_member:- membership = TenantAccountJoin(- tenant_id=tenant_id,- account_id=account_id,- role=TenantAccountRole.NORMAL,- )- create_tenant_member.return_value = membership-- result = TenantService.join_enterprise_workspace_member(- workspace_id=tenant_id,- account_id=account_id,- email="[email protected]",- role=TenantAccountRole.NORMAL,- operator_account_id="operator-1",- session=service_session,- )-- assert result is membership- create_tenant_member.assert_called_once()- call_args = create_tenant_member.call_args- assert call_args.args[0].id == tenant_id- assert call_args.args[1].id == account_id- assert call_args.kwargs == {- "session": service_session,- "role": "normal",- "operator_account_id": "operator-1",- }-- def test_join_enterprise_workspace_member_raises_when_workspace_missing(- self,- sqlite_session_factory: sessionmaker[Session],- ) -> None:- with sqlite_session_factory() as service_session:- account = Account(name="Test User", email="[email protected]")- service_session.add(account)- service_session.flush()- account_id = account.id- service_session.commit()-- with pytest.raises(EnterpriseWorkspaceMemberWorkspaceNotFoundError):- TenantService.join_enterprise_workspace_member(- workspace_id="missing-workspace",- account_id=account_id,- email="[email protected]",- role=TenantAccountRole.NORMAL,- operator_account_id=None,- session=service_session,- )-- def test_join_enterprise_workspace_member_raises_when_account_missing(- self,- sqlite_session_factory: sessionmaker[Session],- ) -> None:- with sqlite_session_factory() as service_session:- tenant = Tenant(name="Test Workspace", status=TenantStatus.NORMAL)- service_session.add(tenant)- service_session.flush()- tenant_id = tenant.id- service_session.commit()-- with pytest.raises(EnterpriseWorkspaceMemberAccountNotFoundError):- TenantService.join_enterprise_workspace_member(- workspace_id=tenant_id,- account_id="missing-account",- email="[email protected]",- role=TenantAccountRole.NORMAL,- operator_account_id=None,- session=service_session,- )-- # ==================== Member Removal Tests ====================-- def test_remove_pending_member_deletes_orphaned_account(- self, sqlite_session_factory: sessionmaker[Session]- ) -> None:- """Test that removing a pending member with no other workspaces deletes the account."""- with sqlite_session_factory() as service_session:- tenant = Tenant(name="Test Workspace")- operator = Account(name="Operator", email="[email protected]")- pending_member = Account(name="Pending Member", email="[email protected]", status=AccountStatus.PENDING)- service_session.add_all([tenant, operator, pending_member])- service_session.flush()- self._add_tenant_account_join(service_session, tenant, operator.id, TenantAccountRole.OWNER)- member_join = self._add_tenant_account_join(- service_session,- tenant,- pending_member.id,- TenantAccountRole.NORMAL,- )- service_session.flush()- tenant_id = tenant.id- member_id = pending_member.id- member_join_id = member_join.id- service_session.commit()-- with (- patch("services.enterprise.account_deletion_sync.sync_workspace_member_removal") as mock_sync,- ):- mock_sync.return_value = True-- TenantService.remove_member_from_tenant(- tenant,- pending_member,- operator,- session=service_session,- )-- mock_sync.assert_called_once_with(- workspace_id=tenant_id,- member_id=member_id,- source="workspace_member_removed",- )-- with sqlite_session_factory() as assertion_session:- assert assertion_session.get(TenantAccountJoin, member_join_id) is None- assert assertion_session.get(Account, member_id) is None-- def test_remove_pending_member_keeps_account_with_other_workspaces(- self, sqlite_session_factory: sessionmaker[Session]- ) -> None:- """Test that removing a pending member who belongs to other workspaces preserves the account."""- with sqlite_session_factory() as service_session:- tenant = Tenant(name="Test Workspace")- other_tenant = Tenant(name="Other Workspace")- operator = Account(name="Operator", email="[email protected]")- pending_member = Account(name="Pending Member", email="[email protected]", status=AccountStatus.PENDING)- service_session.add_all([tenant, other_tenant, operator, pending_member])- service_session.flush()- self._add_tenant_account_join(service_session, tenant, operator.id, TenantAccountRole.OWNER)- member_join = self._add_tenant_account_join(- service_session,- tenant,- pending_member.id,- TenantAccountRole.NORMAL,- )- other_member_join = self._add_tenant_account_join(- service_session,- other_tenant,- pending_member.id,- TenantAccountRole.NORMAL,- )- service_session.flush()- tenant_id = tenant.id- member_id = pending_member.id- member_join_id = member_join.id- other_member_join_id = other_member_join.id- service_session.commit()-- with (- patch("services.enterprise.account_deletion_sync.sync_workspace_member_removal") as mock_sync,- ):- mock_sync.return_value = True-- TenantService.remove_member_from_tenant(- tenant,- pending_member,- operator,- session=service_session,- )-- mock_sync.assert_called_once_with(- workspace_id=tenant_id,- member_id=member_id,- source="workspace_member_removed",- )-- with sqlite_session_factory() as assertion_session:- assert assertion_session.get(TenantAccountJoin, member_join_id) is None- assert assertion_session.get(TenantAccountJoin, other_member_join_id) is not None- assert assertion_session.get(Account, member_id) is not None-- def test_remove_active_member_preserves_account(self, sqlite_session_factory: sessionmaker[Session]) -> None:- """Test that removing an active member never deletes the account, even with no other workspaces."""- with sqlite_session_factory() as service_session:- tenant = Tenant(name="Test Workspace")- operator = Account(name="Operator", email="[email protected]")- active_member = Account(name="Active Member", email="[email protected]", status=AccountStatus.ACTIVE)- service_session.add_all([tenant, operator, active_member])- service_session.flush()- self._add_tenant_account_join(service_session, tenant, operator.id, TenantAccountRole.OWNER)- member_join = self._add_tenant_account_join(- service_session,- tenant,- active_member.id,- TenantAccountRole.NORMAL,- )- service_session.flush()- tenant_id = tenant.id- member_id = active_member.id- member_join_id = member_join.id- service_session.commit()-- with (- patch("services.enterprise.account_deletion_sync.sync_workspace_member_removal") as mock_sync,- ):- mock_sync.return_value = True-- TenantService.remove_member_from_tenant(- tenant,- active_member,- operator,- session=service_session,- )-- mock_sync.assert_called_once_with(- workspace_id=tenant_id,- member_id=member_id,- source="workspace_member_removed",- )-- with sqlite_session_factory() as assertion_session:- assert assertion_session.get(TenantAccountJoin, member_join_id) is None- assert assertion_session.get(Account, member_id) is not None-- # ==================== Tenant Switching Tests ====================-- def test_switch_tenant_success(self, sqlite_session_factory: sessionmaker[Session]) -> None:- """Test successful tenant switching."""- with sqlite_session_factory() as service_session:- account = Account(name="Test User", email="[email protected]")- tenant = Tenant(name="Target Workspace")- other_tenant = Tenant(name="Other Workspace")- service_session.add_all([account, tenant, other_tenant])- service_session.flush()- tenant_join = self._add_tenant_account_join(- service_session, tenant, account.id, TenantAccountRole.NORMAL, current=False- )- other_tenant_join = self._add_tenant_account_join(- service_session, other_tenant, account.id, TenantAccountRole.NORMAL, current=True- )- tenant_id = tenant.id- tenant_join_id = tenant_join.id- other_tenant_join_id = other_tenant_join.id- service_session.commit()-- mock_now = datetime(2026, 6, 5, 11, 0, 0)- with patch("services.account_service.naive_utc_now", return_value=mock_now):- TenantService.switch_tenant(account, tenant_id, session=service_session)-- assert account.current_tenant_id == tenant_id-- with sqlite_session_factory() as assertion_session:- tenant_join = assertion_session.get(TenantAccountJoin, tenant_join_id)- other_tenant_join = assertion_session.get(TenantAccountJoin, other_tenant_join_id)- assert tenant_join is not None- assert tenant_join.current is True- assert tenant_join.last_opened_at == mock_now- assert other_tenant_join is not None- assert other_tenant_join.current is False-- def test_switch_tenant_no_tenant_id(self, unbound_session: Session) -> None:- mock_account = TestAccountAssociatedDataFactory.create_account_mock()-- with pytest.raises(ValueError):- TenantService.switch_tenant(mock_account, None, session=unbound_session)-- # ==================== Role Management Tests ====================-- def test_update_member_role_success(self, sqlite_session_factory: sessionmaker[Session]) -> None:- """Test successful member role update."""- with sqlite_session_factory() as service_session:- tenant = Tenant(name="Test Workspace")- service_session.add(tenant)- service_session.flush()- target_join = self._add_tenant_account_join(- service_session,- tenant,- "member-789",- TenantAccountRole.NORMAL,- )- self._add_tenant_account_join(- service_session,- tenant,- "operator-123",- TenantAccountRole.OWNER,- )- service_session.flush()- target_join_id = target_join.id- service_session.commit()-- mock_member = TestAccountAssociatedDataFactory.create_account_mock(account_id="member-789")- mock_operator = TestAccountAssociatedDataFactory.create_account_mock(account_id="operator-123")-- TenantService.update_member_role(- tenant,- mock_member,- "admin",- mock_operator,- session=service_session,- )-- with sqlite_session_factory() as assertion_session:- persisted_target_join = assertion_session.get(TenantAccountJoin, target_join_id)- assert persisted_target_join is not None- assert persisted_target_join.role == TenantAccountRole.ADMIN-- @pytest.mark.parametrize(- ("outgoing_owner_role_tags", "expected_demoted_role_ids"),- [(["owner", "editor"], ["editor-role-id"]), (["owner"], ["no-access-role-id"])],- )- def test_update_member_role_to_owner_rbac_enabled(- self,- sqlite_session: Session,- outgoing_owner_role_tags: list[str],- expected_demoted_role_ids: list[str],- config_overrides: Callable[..., None],- ) -> None:- config_overrides(RBAC_ENABLED=True)- tenant = Tenant(name="Test Workspace")- sqlite_session.add(tenant)- sqlite_session.flush()-- operator = TestAccountAssociatedDataFactory.create_account_mock(account_id="operator-1")- candidate = TestAccountAssociatedDataFactory.create_account_mock(account_id="candidate-1")- self._add_tenant_account_join(sqlite_session, tenant, operator.id, TenantAccountRole.EDITOR)- self._add_tenant_account_join(sqlite_session, tenant, candidate.id, TenantAccountRole.EDITOR)- self._add_tenant_account_join(sqlite_session, tenant, "stale-db-owner", TenantAccountRole.OWNER)- sqlite_session.commit()-- outgoing_owner_roles = MemberRolesResponse(- account_id="real-rbac-owner",- roles=[- RBACRole(id=f"{tag}-role-id", type="workspace", name=tag, role_tag=tag)- for tag in outgoing_owner_role_tags- ],- )-- with (- patch(- "services.account_service.AccountService.get_workspace_permission_keys",- return_value={"workspace.role.manage"},- ),- patch(- "services.account_service.AccountService.get_rbac_workspace_owner_account_id",- return_value="real-rbac-owner",- ),- patch(- "services.account_service.AccountService._resolve_legacy_role_id",- side_effect=lambda *, role, **_kwargs: f"{role.value}-role-id",- ),- patch(- "services.account_service.AccountService._resolve_role_id_by_tag",- return_value="no-access-role-id",- ),- patch("services.account_service.RBACService.MemberRoles.get", return_value=outgoing_owner_roles),- patch("services.account_service.RBACService.MemberRoles.replace") as mock_replace,- ):- TenantService.update_member_role(tenant, candidate, "owner", operator, session=sqlite_session)-- mock_replace.assert_any_call(- tenant_id=tenant.id,- account_id=operator.id,- member_account_id="real-rbac-owner",- role_ids=expected_demoted_role_ids,- session=sqlite_session,- )- assert self._db_role_of(sqlite_session, tenant, "stale-db-owner") == TenantAccountRole.NORMAL- assert self._db_role_of(sqlite_session, tenant, candidate.id) == TenantAccountRole.OWNER-- def test_create_owner_tenant_rbac_enabled_assigns_owner_role(- self,- sqlite_session: Session,- mock_external_service_dependencies: _MockDependencies,- config_overrides: Callable[..., None],- ) -> None:- config_overrides(RBAC_ENABLED=True)- mock_account = TestAccountAssociatedDataFactory.create_account_mock(account_id="user-rbac", name="RBAC User")- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True- mock_external_service_dependencies[- "feature_service"- ].get_license.return_value.workspaces.is_available.return_value = True-- mock_tenant = Tenant(name="RBAC User's Workspace")- mock_tenant.id = "tenant-rbac"- sqlite_session.add(mock_tenant)- sqlite_session.flush()-- with (- patch("services.account_service.TenantService.create_tenant", return_value=mock_tenant),- patch(- "services.account_service.AccountService._resolve_legacy_role_id",- return_value="rbac-owner-id",- ),- patch("services.account_service.RBACService") as mock_rbac_service,- patch("services.account_service.tenant_was_created.send"),- ):- TenantService.create_owner_tenant(mock_account, is_setup=True, session=sqlite_session)-- mock_rbac_service.MemberRoles.replace.assert_called_once_with(- tenant_id="tenant-rbac",- account_id="user-rbac",- member_account_id="user-rbac",- role_ids=["rbac-owner-id"],- session=sqlite_session,- )-- def test_admin_can_update_admin_member_role(self, sqlite_session_factory: sessionmaker[Session]) -> None:- """Test admin can update another non-owner member, including an admin."""- with sqlite_session_factory() as service_session:- tenant = Tenant(name="Test Workspace")- service_session.add(tenant)- service_session.flush()- mock_member = TestAccountAssociatedDataFactory.create_account_mock(account_id="member-789")- mock_operator = TestAccountAssociatedDataFactory.create_account_mock(account_id="operator-123")- target_join = self._add_tenant_account_join(- service_session, tenant, mock_member.id, TenantAccountRole.ADMIN- )- self._add_tenant_account_join(service_session, tenant, mock_operator.id, TenantAccountRole.ADMIN)- service_session.flush()- target_join_id = target_join.id- service_session.commit()-- TenantService.update_member_role(- tenant,- mock_member,- "editor",- mock_operator,- session=service_session,- )-- with sqlite_session_factory() as assertion_session:- persisted_target_join = assertion_session.get(TenantAccountJoin, target_join_id)- assert persisted_target_join is not None- assert persisted_target_join.role == TenantAccountRole.EDITOR-- def test_admin_cannot_update_owner_member_role(self, sqlite_session: Session) -> None:- """Test admin cannot update an owner member."""- tenant = Tenant(name="Test Workspace")- sqlite_session.add(tenant)- sqlite_session.flush()- mock_member = TestAccountAssociatedDataFactory.create_account_mock(account_id="member-789")- mock_operator = TestAccountAssociatedDataFactory.create_account_mock(account_id="operator-123")- self._add_tenant_account_join(sqlite_session, tenant, mock_member.id, TenantAccountRole.OWNER)- self._add_tenant_account_join(sqlite_session, tenant, mock_operator.id, TenantAccountRole.ADMIN)- sqlite_session.commit()-- with pytest.raises(NoPermissionError):- TenantService.update_member_role(tenant, mock_member, "editor", mock_operator, session=sqlite_session)-- def test_admin_cannot_promote_member_to_owner(self, sqlite_session: Session) -> None:- """Test admin cannot promote a non-owner member to owner."""- tenant = Tenant(name="Test Workspace")- sqlite_session.add(tenant)- sqlite_session.flush()- mock_member = TestAccountAssociatedDataFactory.create_account_mock(account_id="member-789")- mock_operator = TestAccountAssociatedDataFactory.create_account_mock(account_id="operator-123")- self._add_tenant_account_join(sqlite_session, tenant, mock_member.id, TenantAccountRole.ADMIN)- self._add_tenant_account_join(sqlite_session, tenant, mock_operator.id, TenantAccountRole.ADMIN)- sqlite_session.commit()-- with pytest.raises(NoPermissionError):- TenantService.update_member_role(tenant, mock_member, "owner", mock_operator, session=sqlite_session)-- # ==================== Permission Check Tests ====================-- def test_check_member_permission_success(self, sqlite_session: Session) -> None:- """Test successful member permission check."""- tenant = Tenant(name="Test Workspace")- sqlite_session.add(tenant)- sqlite_session.flush()- mock_operator = TestAccountAssociatedDataFactory.create_account_mock(account_id="operator-123")- mock_member = TestAccountAssociatedDataFactory.create_account_mock(account_id="member-789")- self._add_tenant_account_join(sqlite_session, tenant, mock_operator.id, TenantAccountRole.OWNER)- sqlite_session.commit()-- TenantService.check_member_permission(tenant, mock_operator, mock_member, "add", session=sqlite_session)-- def test_check_member_permission_operate_self(self, unbound_session: Session) -> None:- """Test member permission check when operator tries to operate self."""- # Setup test data- mock_tenant = _tenant()- mock_tenant.id = "tenant-456"- mock_operator = TestAccountAssociatedDataFactory.create_account_mock(account_id="operator-123")-- # Execute test and verify exception- from services.errors.account import CannotOperateSelfError-- with pytest.raises(CannotOperateSelfError):- TenantService.check_member_permission(- mock_tenant,- mock_operator,- mock_operator, # Same as operator- "add",- session=unbound_session,- )-- def test_admin_can_remove_non_owner_member(self, sqlite_session: Session) -> None:- """Test admin can remove a non-owner member."""- tenant = Tenant(name="Test Workspace")- sqlite_session.add(tenant)- sqlite_session.flush()- mock_operator = TestAccountAssociatedDataFactory.create_account_mock(account_id="operator-123")- mock_member = TestAccountAssociatedDataFactory.create_account_mock(account_id="member-789")- self._add_tenant_account_join(sqlite_session, tenant, mock_operator.id, TenantAccountRole.ADMIN)- self._add_tenant_account_join(sqlite_session, tenant, mock_member.id, TenantAccountRole.ADMIN)- sqlite_session.commit()-- TenantService.check_member_permission(tenant, mock_operator, mock_member, "remove", session=sqlite_session)-- def test_admin_cannot_remove_owner_member(self, sqlite_session: Session) -> None:- """Test admin cannot remove an owner member."""- tenant = Tenant(name="Test Workspace")- sqlite_session.add(tenant)- sqlite_session.flush()- mock_operator = TestAccountAssociatedDataFactory.create_account_mock(account_id="operator-123")- mock_member = TestAccountAssociatedDataFactory.create_account_mock(account_id="member-789")- self._add_tenant_account_join(sqlite_session, tenant, mock_operator.id, TenantAccountRole.ADMIN)- self._add_tenant_account_join(sqlite_session, tenant, mock_member.id, TenantAccountRole.OWNER)- sqlite_session.commit()-- with pytest.raises(NoPermissionError):- TenantService.check_member_permission(tenant, mock_operator, mock_member, "remove", session=sqlite_session)-- def test_rbac_member_can_remove_non_owner_member(- self, sqlite_session: Session, config_overrides: Callable[..., None]- ) -> None:- """Test RBAC workspace.member.manage allows removing a non-owner member."""- config_overrides(RBAC_ENABLED=True)- mock_tenant = _tenant(sqlite_session)- mock_tenant.id = "tenant-456"- mock_operator = TestAccountAssociatedDataFactory.create_account_mock(account_id="operator-123")- mock_member = TestAccountAssociatedDataFactory.create_account_mock(account_id="member-789")-- mock_permissions = MagicMock()- mock_permissions.workspace = MagicMock(permission_keys=["workspace.member.manage"])-- with (- patch("services.account_service.RBACService.MyPermissions.get", return_value=mock_permissions),- patch("services.account_service.AccountService.is_rbac_workspace_owner", return_value=False),- ):- TenantService.check_member_permission(- mock_tenant, mock_operator, mock_member, "remove", session=sqlite_session- )-- def test_rbac_member_cannot_remove_without_permission(- self, sqlite_session: Session, config_overrides: Callable[..., None]- ) -> None:- """Test RBAC permission check rejects removal without workspace.member.manage."""- config_overrides(RBAC_ENABLED=True)- mock_tenant = _tenant(sqlite_session)- mock_tenant.id = "tenant-456"- mock_operator = TestAccountAssociatedDataFactory.create_account_mock(account_id="operator-123")- mock_member = TestAccountAssociatedDataFactory.create_account_mock(account_id="member-789")-- mock_permissions = MagicMock()- mock_permissions.workspace = MagicMock(permission_keys=["workspace.role.manage"])-- with (- patch("services.account_service.RBACService.MyPermissions.get", return_value=mock_permissions),- ):- with pytest.raises(NoPermissionError):- TenantService.check_member_permission(- mock_tenant, mock_operator, mock_member, "remove", session=sqlite_session- )-- def test_rbac_member_cannot_remove_owner_member(- self, sqlite_session: Session, config_overrides: Callable[..., None]- ) -> None:- """Test RBAC permission check rejects removing an owner member."""- config_overrides(RBAC_ENABLED=True)- mock_tenant = _tenant(sqlite_session)- mock_tenant.id = "tenant-456"- mock_operator = TestAccountAssociatedDataFactory.create_account_mock(account_id="operator-123")- mock_member = TestAccountAssociatedDataFactory.create_account_mock(account_id="member-789")-- mock_permissions = MagicMock()- mock_permissions.workspace = MagicMock(permission_keys=["workspace.member.manage"])-- with (- patch("services.account_service.RBACService.MyPermissions.get", return_value=mock_permissions),- patch("services.account_service.AccountService.is_rbac_workspace_owner", return_value=True),- ):- with pytest.raises(NoPermissionError):- TenantService.check_member_permission(- mock_tenant, mock_operator, mock_member, "remove", session=sqlite_session- )-- def test_get_rbac_workspace_owner_account_id(self, sqlite_session: Session) -> None:- mock_roles = Paginated[MembersInRole](data=[MembersInRole(account_id="owner-account")])- mock_rbac_roles = MagicMock()- mock_rbac_roles.members.return_value = mock_roles-- with (- patch(- "services.account_service.AccountService._resolve_legacy_role_id",- return_value="owner-role-id",- ),- patch("services.account_service.RBACService.Roles", mock_rbac_roles),- ):- owner_account_id = AccountService.get_rbac_workspace_owner_account_id(- "tenant-1", "acct-1", session=sqlite_session- )-- assert owner_account_id == "owner-account"- assert not sqlite_session.in_transaction()- call = mock_rbac_roles.members.call_args- assert call.kwargs["tenant_id"] == "tenant-1"- assert call.kwargs["account_id"] == "acct-1"- assert call.kwargs["role_id"] == "owner-role-id"- assert call.kwargs["options"].page_number == 1- assert call.kwargs["options"].results_per_page == 1---class TestRegisterService:- @pytest.fixture(autouse=True)- def _register_config(self, config_overrides: Callable[..., None]) -> None:- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)-- """- Comprehensive unit tests for RegisterService methods.-- This test suite covers all registration-related operations including:- - System setup- - Account registration- - Member invitation- - Token management- - Invitation validation- - Error conditions and edge cases- """-- @pytest.fixture- def mock_redis_dependencies(self) -> Iterator[MagicMock]:- """Mock setup for Redis-related functions."""- with patch("services.account_service.redis_client") as mock_redis:- yield mock_redis-- @pytest.fixture- def mock_external_service_dependencies(self) -> Iterator[_MockDependencies]:- """Mock setup for external service dependencies."""- with (- 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,- ):- yield {- "feature_service": mock_feature_service,- "billing_service": mock_billing_service,- "passport_service": mock_passport_service,- }-- @pytest.fixture- def mock_task_dependencies(self) -> Iterator[MagicMock]:- """Mock setup for task dependencies."""- with patch("services.account_service.send_invite_member_mail_task") as mock_send_mail:- yield mock_send_mail-- # ==================== Setup Tests ====================-- def test_setup_success(- self,- sqlite_session_factory: sessionmaker[Session],- mock_external_service_dependencies: _MockDependencies,- ) -> None:- """Test successful system setup."""- # 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-- # Mock AccountService.create_account- mock_account = TestAccountAssociatedDataFactory.create_account_mock()- with patch("services.account_service.AccountService.create_account") as mock_create_account:- mock_create_account.return_value = mock_account-- with (- patch("services.account_service.TenantService.create_owner_tenant_if_not_exist") as mock_create_tenant,- patch("services.account_service.CommunityTelemetryService.report_install") as mock_report_install,- ):- with sqlite_session_factory() as service_session:- RegisterService.setup(- "[email protected]",- "Admin User",- "password123",- "192.168.1.1",- "en-US",- session=service_session,- )-- mock_create_account.assert_called_once_with(- email="[email protected]",- name="Admin User",- interface_language="en-US",- password="password123",- is_setup=True,- ip_address="192.168.1.1",- session=service_session,- )- mock_create_tenant.assert_called_once_with(- account=mock_account,- is_setup=True,- session=service_session,- )- mock_report_install.assert_called_once_with(session=service_session)-- with sqlite_session_factory() as assertion_session:- dify_setup = assertion_session.scalar(select(DifySetup))- assert dify_setup is not None- assert dify_setup.instance_id is not None- assert str(UUID(dify_setup.instance_id)) == dify_setup.instance_id- assert dify_setup.install_reported_at is None- assert dify_setup.last_heartbeat_at is None-- def test_setup_succeeds_when_telemetry_install_report_fails(- self,- sqlite_session_factory: sessionmaker[Session],- mock_external_service_dependencies: _MockDependencies,- ) -> None:- 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- mock_account = TestAccountAssociatedDataFactory.create_account_mock()-- with (- patch("services.account_service.AccountService.create_account", return_value=mock_account),- patch("services.account_service.TenantService.create_owner_tenant_if_not_exist"),- patch(- "services.account_service.CommunityTelemetryService.report_install",- side_effect=RuntimeError("telemetry unavailable"),- ),- ):- with sqlite_session_factory() as service_session:- RegisterService.setup(- "[email protected]",- "Admin User",- "password123",- "192.168.1.1",- "en-US",- session=service_session,- )-- with sqlite_session_factory() as assertion_session:- assert assertion_session.scalar(select(DifySetup)) is not None-- def test_setup_failure_cleans_partially_persisted_account(- self,- sqlite_session_factory: sessionmaker[Session],- mock_external_service_dependencies: _MockDependencies,- ) -> None:- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- mock_external_service_dependencies[- "feature_service"- ].get_license.return_value.seats.is_available.return_value = True- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- with patch(- "services.account_service.TenantService.create_owner_tenant_if_not_exist",- side_effect=RuntimeError("tenant creation failed"),- ):- with sqlite_session_factory() as service_session:- with pytest.raises(ValueError, match="Setup failed: tenant creation failed"):- RegisterService.setup(- "[email protected]",- "Admin User",- "password123",- "192.168.1.1",- "en-US",- session=service_session,- )-- with sqlite_session_factory() as assertion_session:- assert assertion_session.scalar(select(Account).where(Account.email == "[email protected]")) is None- assert assertion_session.scalar(select(DifySetup)) is None-- # ==================== Registration Tests ====================-- def test_create_account_and_tenant_calls_default_workspace_join_for_enterprise_edition(- self,- sqlite_session: Session,- mock_external_service_dependencies: _MockDependencies,- config_overrides: Callable[..., None],- ) -> None:- """Enterprise-only side effect should be invoked for the ENTERPRISE edition."""- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)-- 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-- mock_account = TestAccountAssociatedDataFactory.create_account_mock(- account_id="11111111-1111-1111-1111-111111111111"- )-- with (- patch("services.account_service.AccountService.create_account") as mock_create_account,- patch("services.account_service.TenantService.create_owner_tenant_if_not_exist") as mock_create_workspace,- patch("services.enterprise.enterprise_service.try_join_default_workspace") as mock_join_default_workspace,- ):- mock_create_account.return_value = mock_account-- result = AccountService.create_account_and_tenant(- email="[email protected]",- name="Test User",- interface_language="en-US",- password=None,- ip_address="203.0.113.10",- session=sqlite_session,- )-- assert result == mock_account- mock_create_account.assert_called_once_with(- email="[email protected]",- name="Test User",- interface_language="en-US",- password=None,- timezone=None,- ip_address="203.0.113.10",- check_normalized_email=False,- session=sqlite_session,- )- mock_create_workspace.assert_called_once_with(account=mock_account, session=sqlite_session)- mock_join_default_workspace.assert_called_once_with(mock_account.id)-- def test_create_account_and_tenant_skips_default_workspace_join_for_community_edition(- self,- sqlite_session: Session,- mock_external_service_dependencies: _MockDependencies,- ) -> None:- """Enterprise-only side effect should not be invoked for the COMMUNITY edition."""-- 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-- mock_account = TestAccountAssociatedDataFactory.create_account_mock(- account_id="11111111-1111-1111-1111-111111111111"- )-- with (- patch("services.account_service.AccountService.create_account") as mock_create_account,- patch("services.account_service.TenantService.create_owner_tenant_if_not_exist") as mock_create_workspace,- patch("services.enterprise.enterprise_service.try_join_default_workspace") as mock_join_default_workspace,- ):- mock_create_account.return_value = mock_account-- AccountService.create_account_and_tenant(- email="[email protected]",- name="Test User",- interface_language="en-US",- password=None,- session=sqlite_session,- )-- mock_create_workspace.assert_called_once_with(account=mock_account, session=sqlite_session)- mock_join_default_workspace.assert_not_called()-- def test_create_account_and_tenant_still_calls_default_workspace_join_when_workspace_creation_fails(- self,- sqlite_session: Session,- mock_external_service_dependencies: _MockDependencies,- config_overrides: Callable[..., None],- ) -> None:- """Default workspace join should still be attempted when personal workspace creation fails."""- from services.errors.workspace import WorkSpaceNotAllowedCreateError-- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- 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-- mock_account = TestAccountAssociatedDataFactory.create_account_mock(- account_id="11111111-1111-1111-1111-111111111111"- )-- with (- patch("services.account_service.AccountService.create_account") as mock_create_account,- patch("services.account_service.TenantService.create_owner_tenant_if_not_exist") as mock_create_workspace,- patch("services.enterprise.enterprise_service.try_join_default_workspace") as mock_join_default_workspace,- ):- mock_create_account.return_value = mock_account- mock_create_workspace.side_effect = WorkSpaceNotAllowedCreateError()-- with pytest.raises(WorkSpaceNotAllowedCreateError):- AccountService.create_account_and_tenant(- email="[email protected]",- name="Test User",- interface_language="en-US",- password=None,- session=sqlite_session,- )-- mock_join_default_workspace.assert_called_once_with(mock_account.id)-- def test_register_success(- self, sqlite_session: Session, mock_external_service_dependencies: _MockDependencies- ) -> None:- """Test successful account registration."""- # Setup mocks- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True- mock_external_service_dependencies[- "feature_service"- ].get_license.return_value.workspaces.is_available.return_value = True- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- # Mock AccountService.create_account- mock_account = TestAccountAssociatedDataFactory.create_account_mock()- with patch("services.account_service.AccountService.create_account") as mock_create_account:- mock_create_account.return_value = mock_account-- with (- patch("services.account_service.TenantService.create_owner_tenant") as mock_create_owner_tenant,- ):- # Execute test- result = RegisterService.register(- email="[email protected]",- name="Test User",- password="password123",- language="en-US",- ip_address="203.0.113.10",- session=sqlite_session,- )-- # Verify results- assert result == mock_account- assert result.status == "active"- assert result.initialized_at is not None- mock_create_account.assert_called_once_with(- email="[email protected]",- name="Test User",- interface_language="en-US",- password="password123",- is_setup=False,- timezone=None,- ip_address="203.0.113.10",- check_normalized_email=True,- session=sqlite_session,- )- mock_create_owner_tenant.assert_called_once_with(mock_account, session=sqlite_session)-- def test_register_rejects_existing_normalized_email(- self,- sqlite_session: Session,- mock_external_service_dependencies: _MockDependencies,- ) -> None:- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- sqlite_session.add(- Account(- name="Existing User",- email="[email protected]",- normalized_email="[email protected]",- )- )- sqlite_session.commit()-- with pytest.raises(AccountEmailAlreadyInUseError):- RegisterService.register(- email="[email protected]",- name="New User",- language="en-US",- create_workspace_required=False,- session=sqlite_session,- )-- def test_register_calls_default_workspace_join_for_enterprise_edition(- self,- sqlite_session: Session,- mock_external_service_dependencies: _MockDependencies,- config_overrides: Callable[..., None],- ) -> None:- """Enterprise-only side effect should be invoked after successful register commit."""- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)-- 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-- mock_account = TestAccountAssociatedDataFactory.create_account_mock(- account_id="11111111-1111-1111-1111-111111111111"- )-- with (- patch("services.account_service.AccountService.create_account") as mock_create_account,- patch("services.enterprise.enterprise_service.try_join_default_workspace") as mock_join_default_workspace,- ):- mock_create_account.return_value = mock_account-- result = RegisterService.register(- email="[email protected]",- name="Test User",- password="password123",- language="en-US",- create_workspace_required=False,- session=sqlite_session,- )-- assert result == mock_account- mock_join_default_workspace.assert_called_once_with(mock_account.id)-- def test_register_skips_default_workspace_join_for_community_edition(- self,- sqlite_session: Session,- mock_external_service_dependencies: _MockDependencies,- ) -> None:- """Enterprise-only side effect should not be invoked for the COMMUNITY edition."""-- 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-- mock_account = TestAccountAssociatedDataFactory.create_account_mock(- account_id="11111111-1111-1111-1111-111111111111"- )-- with (- patch("services.account_service.AccountService.create_account") as mock_create_account,- patch("services.enterprise.enterprise_service.try_join_default_workspace") as mock_join_default_workspace,- ):- mock_create_account.return_value = mock_account-- RegisterService.register(- email="[email protected]",- name="Test User",- password="password123",- language="en-US",- create_workspace_required=False,- session=sqlite_session,- )-- mock_join_default_workspace.assert_not_called()-- def test_register_still_calls_default_workspace_join_when_personal_workspace_creation_fails(- self,- sqlite_session: Session,- mock_external_service_dependencies: _MockDependencies,- config_overrides: Callable[..., None],- ) -> None:- """Default workspace join should run even when personal workspace creation raises."""- from services.errors.workspace import WorkSpaceNotAllowedCreateError-- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True- mock_external_service_dependencies[- "feature_service"- ].get_license.return_value.workspaces.is_available.return_value = True- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- mock_account = TestAccountAssociatedDataFactory.create_account_mock(- account_id="11111111-1111-1111-1111-111111111111"- )-- with (- patch("services.account_service.AccountService.create_account") as mock_create_account,- patch("services.account_service.TenantService.create_tenant") as mock_create_tenant,- patch("services.enterprise.enterprise_service.try_join_default_workspace") as mock_join_default_workspace,- ):- mock_create_account.return_value = mock_account- mock_create_tenant.side_effect = WorkSpaceNotAllowedCreateError()-- with pytest.raises(AccountRegisterError, match="Workspace is not allowed to create."):- RegisterService.register(- email="[email protected]",- name="Test User",- password="password123",- language="en-US",- session=sqlite_session,- )-- mock_join_default_workspace.assert_called_once_with(mock_account.id)-- def test_register_still_calls_default_workspace_join_when_workspace_limit_exceeded(- self,- sqlite_session: Session,- mock_external_service_dependencies: _MockDependencies,- config_overrides: Callable[..., None],- ) -> None:- """Default workspace join should run before propagating workspace-limit registration failure."""- from services.errors.workspace import WorkspacesLimitExceededError-- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True- mock_external_service_dependencies[- "feature_service"- ].get_license.return_value.workspaces.is_available.return_value = True- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- mock_account = TestAccountAssociatedDataFactory.create_account_mock(- account_id="11111111-1111-1111-1111-111111111111"- )-- with (- patch("services.account_service.AccountService.create_account") as mock_create_account,- patch("services.account_service.TenantService.create_tenant") as mock_create_tenant,- patch("services.enterprise.enterprise_service.try_join_default_workspace") as mock_join_default_workspace,- ):- mock_create_account.return_value = mock_account- mock_create_tenant.side_effect = WorkspacesLimitExceededError()-- with pytest.raises(AccountRegisterError, match="Registration failed:"):- RegisterService.register(- email="[email protected]",- name="Test User",- password="password123",- language="en-US",- session=sqlite_session,- )-- mock_join_default_workspace.assert_called_once_with(mock_account.id)-- def test_register_with_pending_status(- self, sqlite_session: Session, mock_external_service_dependencies: _MockDependencies- ) -> None:- """Test account registration with pending status."""- # Setup mocks- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True- mock_external_service_dependencies[- "feature_service"- ].get_license.return_value.workspaces.is_available.return_value = True- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- # Mock AccountService.create_account- mock_account = TestAccountAssociatedDataFactory.create_account_mock()- with patch("services.account_service.AccountService.create_account") as mock_create_account:- mock_create_account.return_value = mock_account-- # Mock TenantService methods- with (- patch("services.account_service.TenantService.create_tenant") as mock_create_tenant,- patch("services.account_service.TenantService.create_tenant_member") as mock_create_member,- patch("services.account_service.tenant_was_created") as mock_event,- ):- mock_tenant = Tenant(name="Test User's Workspace")- sqlite_session.add(mock_tenant)- sqlite_session.flush()- mock_create_tenant.return_value = mock_tenant- mock_create_member.side_effect = lambda tenant, account, session, role: session.add(- TenantAccountJoin(- tenant_id=tenant.id,- account_id=account.id,- role=TenantAccountRole(role),- )- )-- # Execute test with pending status- from models.account import AccountStatus-- result = RegisterService.register(- email="[email protected]",- name="Test User",- password="password123",- language="en-US",- status=AccountStatus.PENDING,- session=sqlite_session,- )-- # Verify results- assert result == mock_account- assert result.status == "pending"-- def test_register_workspace_not_allowed(- self, sqlite_session: Session, mock_external_service_dependencies: _MockDependencies- ) -> None:- """Test registration when workspace creation is not allowed."""- # Setup mocks- mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = True- mock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = True- mock_external_service_dependencies[- "feature_service"- ].get_license.return_value.workspaces.is_available.return_value = True- mock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False-- # Mock AccountService.create_account- mock_account = TestAccountAssociatedDataFactory.create_account_mock()- with patch("services.account_service.AccountService.create_account") as mock_create_account:- mock_create_account.return_value = mock_account-- # Execute test and verify exception- from services.errors.workspace import WorkSpaceNotAllowedCreateError-- with patch("services.account_service.TenantService.create_tenant") as mock_create_tenant:- mock_create_tenant.side_effect = WorkSpaceNotAllowedCreateError()-- with pytest.raises(AccountRegisterError):- RegisterService.register(- email="[email protected]",- name="Test User",- password="password123",- language="en-US",- session=sqlite_session,- )-- assert sqlite_session.scalar(select(Account).where(Account.email == "[email protected]")) is None-- def test_register_general_exception(- self, sqlite_session: Session, mock_external_service_dependencies: _MockDependencies- ) -> None:- """Test registration with general exception handling."""- # 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-- # Mock AccountService.create_account to raise exception- with patch("services.account_service.AccountService.create_account") as mock_create_account:- mock_create_account.side_effect = Exception("Unexpected error")-- # Execute test and verify exception- with pytest.raises(AccountRegisterError):- RegisterService.register(- email="[email protected]",- name="Test User",- password="password123",- language="en-US",- session=sqlite_session,- )-- assert sqlite_session.scalar(select(Account).where(Account.email == "[email protected]")) is None-- # ==================== Member Invitation Tests ====================-- @pytest.mark.usefixtures("mock_task_dependencies")- def test_invite_new_member_new_account(self, sqlite_session: Session) -> None:- """Test inviting a new member who doesn't have an account."""- # Setup test data- mock_tenant = _tenant(sqlite_session)- mock_tenant.id = "tenant-456"- mock_tenant.name = "Test Workspace"- mock_inviter = TestAccountAssociatedDataFactory.create_account_mock(account_id="inviter-123", name="Inviter")-- with (- patch("services.account_service.AccountService.get_account_by_email_with_case_fallback") as mock_lookup,- ):- mock_lookup.return_value = None-- # Mock RegisterService.register- mock_new_account = TestAccountAssociatedDataFactory.create_account_mock(- account_id="new-user-456", email="[email protected]", name="newuser", status="pending"- )- with patch("services.account_service.RegisterService.register") as mock_register:- mock_register.return_value = mock_new_account-- # Mock TenantService methods- with (- patch("services.account_service.TenantService.check_member_permission") as mock_check_permission,- patch("services.account_service.TenantService.create_tenant_member") as mock_create_member,- patch("services.account_service.TenantService.switch_tenant") as mock_switch_tenant,- patch("services.account_service.RegisterService.generate_invite_token") as mock_generate_token,- ):- mock_generate_token.return_value = "invite-token-123"-- # Execute test- result = RegisterService.invite_new_member(- tenant=mock_tenant,- email="[email protected]",- language="en-US",- role="normal",- inviter=mock_inviter,- session=sqlite_session,- )-- # Verify results- assert result == "invite-token-123"- mock_register.assert_called_once_with(- email="[email protected]",- name="newuser",- language="en-US",- status=AccountStatus.PENDING,- is_setup=True,- check_normalized_email=True,- session=sqlite_session,- )- mock_lookup.assert_called_once_with("[email protected]", session=sqlite_session)-- def test_invite_new_member_normalizes_new_account_email(- self, sqlite_session: Session, mock_task_dependencies: MagicMock- ) -> None:- """Ensure inviting with mixed-case email normalizes before registering."""- mock_tenant = _tenant(sqlite_session)- mock_tenant.id = "tenant-456"- mock_inviter = TestAccountAssociatedDataFactory.create_account_mock(account_id="inviter-123", name="Inviter")- mixed_email = "[email protected]"-- with (- patch("services.account_service.AccountService.get_account_by_email_with_case_fallback") as mock_lookup,- ):- mock_lookup.return_value = None-- mock_new_account = TestAccountAssociatedDataFactory.create_account_mock(- account_id="new-user-789", email="[email protected]", name="invitee", status="pending"- )- with patch("services.account_service.RegisterService.register") as mock_register:- mock_register.return_value = mock_new_account- with (- patch("services.account_service.TenantService.check_member_permission") as mock_check_permission,- patch("services.account_service.TenantService.create_tenant_member") as mock_create_member,- patch("services.account_service.TenantService.switch_tenant") as mock_switch_tenant,- patch("services.account_service.RegisterService.generate_invite_token") as mock_generate_token,- ):- mock_generate_token.return_value = "invite-token-abc"-- RegisterService.invite_new_member(- tenant=mock_tenant,- email=mixed_email,- language="en-US",- role="normal",- inviter=mock_inviter,- session=sqlite_session,- )-- mock_register.assert_called_once_with(- email="[email protected]",- name="invitee",- language="en-US",- status=AccountStatus.PENDING,- is_setup=True,- check_normalized_email=True,- session=sqlite_session,- )- mock_lookup.assert_called_once_with(mixed_email, session=sqlite_session)- mock_check_permission.assert_called_once_with(- mock_tenant,- mock_inviter,- None,- "add",- session=sqlite_session,- )- mock_create_member.assert_called_once_with(- mock_tenant,- mock_new_account,- sqlite_session,- "normal",- operator_account_id=mock_inviter.id,- )- mock_switch_tenant.assert_called_once_with(mock_new_account, mock_tenant.id, session=sqlite_session)- mock_generate_token.assert_called_once_with(- mock_tenant, mock_new_account, "normal", requires_setup=True- )- mock_task_dependencies.delay.assert_called_once()-- def test_invite_new_member_existing_account(- self, sqlite_session: Session, mock_task_dependencies: MagicMock- ) -> None:- """Test inviting a pending account that is not in the tenant yet."""- # Setup test data- mock_tenant = _tenant(sqlite_session)- mock_tenant.id = "tenant-456"- mock_tenant.name = "Test Workspace"- mock_inviter = TestAccountAssociatedDataFactory.create_account_mock(account_id="inviter-123", name="Inviter")- mock_existing_account = TestAccountAssociatedDataFactory.create_account_mock(- account_id="existing-user-456", email="[email protected]", status="pending"- )-- with (- patch("services.account_service.AccountService.get_account_by_email_with_case_fallback") as mock_lookup,- ):- mock_lookup.return_value = mock_existing_account-- # Mock TenantService methods- with (- patch("services.account_service.TenantService.check_member_permission") as mock_check_permission,- patch("services.account_service.TenantService.create_tenant_member") as mock_create_member,- patch("services.account_service.RegisterService.generate_invite_token") as mock_generate_token,- ):- mock_generate_token.return_value = "invite-token-123"-- # Execute test- result = RegisterService.invite_new_member(- tenant=mock_tenant,- email="[email protected]",- language="en-US",- role="normal",- inviter=mock_inviter,- session=sqlite_session,- )-- # Verify results- assert result == "invite-token-123"- mock_create_member.assert_called_once_with(- mock_tenant,- mock_existing_account,- sqlite_session,- "normal",- operator_account_id=mock_inviter.id,- )- mock_generate_token.assert_called_once_with(- mock_tenant, mock_existing_account, "normal", requires_setup=True- )- mock_task_dependencies.delay.assert_called_once()- mock_lookup.assert_called_once_with("[email protected]", session=sqlite_session)-- def test_invite_existing_active_account_requires_acceptance_before_joining(- self, sqlite_session: Session, mock_task_dependencies: MagicMock- ) -> None:- """Existing active accounts outside the tenant receive an invite without immediate membership."""- mock_tenant = _tenant(sqlite_session)- mock_tenant.id = "tenant-456"- mock_tenant.name = "Test Workspace"- mock_inviter = TestAccountAssociatedDataFactory.create_account_mock(account_id="inviter-123", name="Inviter")- mock_existing_account = TestAccountAssociatedDataFactory.create_account_mock(- account_id="existing-user-456", email="[email protected]", status="active"- )-- with patch("services.account_service.AccountService.get_account_by_email_with_case_fallback") as mock_lookup:- mock_lookup.return_value = mock_existing_account-- with (- patch("services.account_service.TenantService.check_member_permission") as mock_check_permission,- patch("services.account_service.TenantService.create_tenant_member") as mock_create_member,- patch("services.account_service.RegisterService.generate_invite_token") as mock_generate_token,- ):- mock_generate_token.return_value = "invite-token-123"-- result = RegisterService.invite_new_member(- tenant=mock_tenant,- email="[email protected]",- language="en-US",- role="admin",- inviter=mock_inviter,- session=sqlite_session,- )-- assert result == "invite-token-123"- mock_check_permission.assert_called_once_with(- mock_tenant,- mock_inviter,- mock_existing_account,- "add",- session=sqlite_session,- )- mock_create_member.assert_not_called()- mock_generate_token.assert_called_once_with(- mock_tenant, mock_existing_account, "admin", requires_setup=False- )- mock_task_dependencies.delay.assert_called_once()-- def test_invite_new_member_already_in_tenant(self, sqlite_session: Session) -> None:- """Test inviting a member who is already in the tenant."""- # Setup test data- mock_tenant = _tenant(sqlite_session)- mock_tenant.id = "tenant-456"- mock_inviter = TestAccountAssociatedDataFactory.create_account_mock(account_id="inviter-123", name="Inviter")- mock_existing_account = TestAccountAssociatedDataFactory.create_account_mock(- account_id="existing-user-456", email="[email protected]", status="active"- )-- sqlite_session.add(- TenantAccountJoin(- tenant_id=mock_tenant.id,- account_id=mock_existing_account.id,- role=TenantAccountRole.NORMAL,- )- )- sqlite_session.commit()-- # Mock TenantService methods- with (- patch("services.account_service.AccountService.get_account_by_email_with_case_fallback") as mock_lookup,- patch("services.account_service.TenantService.check_member_permission") as mock_check_permission,- ):- mock_lookup.return_value = mock_existing_account- # Execute test and verify exception- with pytest.raises(AccountAlreadyInTenantError):- RegisterService.invite_new_member(- tenant=mock_tenant,- email="[email protected]",- language="en-US",- role="normal",- inviter=mock_inviter,- session=sqlite_session,- )- mock_lookup.assert_called_once()-- def test_invite_new_member_no_inviter(self, unbound_session: Session) -> None:- """Test inviting a member without providing an inviter."""- # Setup test data- mock_tenant = _tenant()-- # Execute test and verify exception- with pytest.raises(ValueError):- RegisterService.invite_new_member(- tenant=mock_tenant,- email="[email protected]",- language="en-US",- role="normal",- inviter=None,- session=unbound_session,- )-- # ==================== RBAC Member Invitation Tests ====================-- @pytest.mark.usefixtures("mock_task_dependencies")- def test_invite_new_member_rbac_enabled_new_account(- self, sqlite_session: Session, config_overrides: Callable[..., None]- ) -> None:- """When RBAC is enabled, create the member join and replace RBAC member roles."""- config_overrides(RBAC_ENABLED=True)- mock_tenant = _tenant(sqlite_session)- mock_tenant.id = "tenant-789"- mock_inviter = TestAccountAssociatedDataFactory.create_account_mock(account_id="inviter-456", name="Inviter")-- with (- patch("services.account_service.AccountService.get_account_by_email_with_case_fallback") as mock_lookup,- ):- mock_lookup.return_value = None-- mock_new_account = TestAccountAssociatedDataFactory.create_account_mock(- account_id="new-user-rbac", email="[email protected]", name="rbacuser", status="pending"- )- with (- patch("services.account_service.RegisterService.register") as mock_register,- patch("services.account_service.TenantService.check_member_permission"),- patch("services.account_service.TenantService.create_tenant_member") as mock_create_member,- patch("services.account_service.TenantService.switch_tenant"),- patch("services.account_service.RegisterService.generate_invite_token", return_value="rbac-token"),- patch("services.account_service.RBACService") as mock_rbac_service,- ):- mock_register.return_value = mock_new_account-- result = RegisterService.invite_new_member(- tenant=mock_tenant,- email="[email protected]",- language="en-US",- role="rbac-role-id-123",- inviter=mock_inviter,- session=sqlite_session,- )-- assert result == "rbac-token"- mock_create_member.assert_called_once_with(- mock_tenant,- mock_new_account,- sqlite_session,- TenantAccountRole.NORMAL.value,- operator_account_id=mock_inviter.id,- )- mock_rbac_service.MemberRoles.replace.assert_called_once_with(- tenant_id=mock_tenant.id,- account_id=mock_inviter.id,- member_account_id=mock_new_account.id,- role_ids=["rbac-role-id-123"],- session=sqlite_session,- )-- @pytest.mark.usefixtures("mock_task_dependencies")- def test_invite_new_member_rbac_enabled_existing_account(- self, sqlite_session: Session, config_overrides: Callable[..., None]- ) -> None:- """When RBAC is enabled and account exists, create the member join and replace RBAC member roles."""- config_overrides(RBAC_ENABLED=True)- mock_tenant = _tenant(sqlite_session)- mock_tenant.id = "tenant-789"- mock_inviter = TestAccountAssociatedDataFactory.create_account_mock(account_id="inviter-456", name="Inviter")- mock_existing_account = TestAccountAssociatedDataFactory.create_account_mock(- account_id="existing-rbac", email="[email protected]", status="pending"- )-- with (- patch("services.account_service.AccountService.get_account_by_email_with_case_fallback") as mock_lookup,- ):- mock_lookup.return_value = mock_existing_account-- with (- patch("services.account_service.TenantService.check_member_permission"),- patch("services.account_service.TenantService.create_tenant_member") as mock_create_member,- patch("services.account_service.RegisterService.generate_invite_token", return_value="rbac-token"),- patch("services.account_service.RBACService") as mock_rbac_service,- ):- result = RegisterService.invite_new_member(- tenant=mock_tenant,- email="[email protected]",- language="en-US",- role="rbac-role-id-456",- inviter=mock_inviter,- session=sqlite_session,- )-- assert result == "rbac-token"- mock_create_member.assert_called_once_with(- mock_tenant,- mock_existing_account,- sqlite_session,- TenantAccountRole.NORMAL.value,- operator_account_id=mock_inviter.id,- )- mock_rbac_service.MemberRoles.replace.assert_called_once_with(- tenant_id=mock_tenant.id,- account_id=mock_inviter.id,- member_account_id=mock_existing_account.id,- role_ids=["rbac-role-id-456"],- session=sqlite_session,- )-- def test_invite_new_member_rbac_enabled_existing_active_account_adds_role_before_signin_response(- self,- sqlite_session: Session,- mock_task_dependencies: MagicMock,- config_overrides: Callable[..., None],- ) -> None:- """Existing active accounts still need an RBAC membership before the API returns the signin URL."""- config_overrides(RBAC_ENABLED=True)- mock_tenant = _tenant(sqlite_session)- mock_tenant.id = "tenant-789"- mock_inviter = TestAccountAssociatedDataFactory.create_account_mock(account_id="inviter-456", name="Inviter")- mock_existing_account = TestAccountAssociatedDataFactory.create_account_mock(- account_id="existing-rbac", email="[email protected]", status=AccountStatus.ACTIVE- )-- with (- patch("services.account_service.AccountService.get_account_by_email_with_case_fallback") as mock_lookup,- ):- mock_lookup.return_value = mock_existing_account-- with (- patch("services.account_service.TenantService.check_member_permission"),- patch("services.account_service.TenantService.create_tenant_member") as mock_create_member,- patch("services.account_service.RBACService") as mock_rbac_service,- ):- with pytest.raises(AccountAlreadyInTenantError):- RegisterService.invite_new_member(- tenant=mock_tenant,- email="[email protected]",- language="en-US",- role="rbac-role-id-456",- inviter=mock_inviter,- session=sqlite_session,- )-- mock_create_member.assert_called_once_with(- mock_tenant,- mock_existing_account,- sqlite_session,- TenantAccountRole.NORMAL.value,- operator_account_id=mock_inviter.id,- )- mock_rbac_service.MemberRoles.replace.assert_called_once_with(- tenant_id=mock_tenant.id,- account_id=mock_inviter.id,- member_account_id=mock_existing_account.id,- role_ids=["rbac-role-id-456"],- session=sqlite_session,- )- mock_task_dependencies.delay.assert_not_called()-- @pytest.mark.usefixtures("mock_task_dependencies")- def test_invite_new_member_rbac_disabled_uses_legacy_role(- self, sqlite_session: Session, config_overrides: Callable[..., None]- ) -> None:- """When RBAC is disabled, create_tenant_member should be called and MemberRoles.replace should NOT."""- config_overrides(RBAC_ENABLED=False)- mock_tenant = _tenant(sqlite_session)- mock_tenant.id = "tenant-legacy"- mock_inviter = TestAccountAssociatedDataFactory.create_account_mock(account_id="inviter-789", name="Inviter")-- with (- patch("services.account_service.AccountService.get_account_by_email_with_case_fallback") as mock_lookup,- ):- mock_lookup.return_value = None-- mock_new_account = TestAccountAssociatedDataFactory.create_account_mock(- account_id="legacy-user", email="[email protected]", name="legacyuser", status="pending"- )- with (- patch("services.account_service.RegisterService.register") as mock_register,- patch("services.account_service.TenantService.check_member_permission"),- patch("services.account_service.TenantService.create_tenant_member") as mock_create_member,- patch("services.account_service.TenantService.switch_tenant"),- patch("services.account_service.RegisterService.generate_invite_token", return_value="legacy-token"),- patch("services.account_service.RBACService") as mock_rbac_service,- ):- mock_register.return_value = mock_new_account-- result = RegisterService.invite_new_member(- tenant=mock_tenant,- email="[email protected]",- language="en-US",- role="editor",- inviter=mock_inviter,- session=sqlite_session,- )-- assert result == "legacy-token"- mock_create_member.assert_called_once_with(- mock_tenant,- mock_new_account,- sqlite_session,- "editor",- operator_account_id=mock_inviter.id,- )- mock_rbac_service.MemberRoles.replace.assert_not_called()-- # ==================== Token Management Tests ====================-- def test_generate_invite_token_success(self, mock_redis_dependencies: MagicMock) -> None:- """Test successful invite token generation."""- # Setup test data- mock_tenant = _tenant()- mock_tenant.id = "tenant-456"- mock_account = TestAccountAssociatedDataFactory.create_account_mock(- account_id="user-123", email="[email protected]"- )-- # Mock uuid generation- with patch("services.account_service.uuid.uuid4") as mock_uuid:- mock_uuid.return_value = "test-uuid-123"-- # Execute test- result = RegisterService.generate_invite_token(mock_tenant, mock_account, "admin", requires_setup=True)-- # Verify results- assert result == "test-uuid-123"- mock_redis_dependencies.setex.assert_called_once()-- # Verify the stored data- call_args = mock_redis_dependencies.setex.call_args- assert call_args[0][0] == "member_invite:token:test-uuid-123"- stored_data = json.loads(call_args[0][2])- assert stored_data["account_id"] == "user-123"- assert stored_data["email"] == "[email protected]"- assert stored_data["workspace_id"] == "tenant-456"- assert stored_data["role"] == "admin"- assert stored_data["requires_setup"] is True-- def test_revoke_token_with_workspace_and_email(self, mock_redis_dependencies: MagicMock) -> None:- """Test revoking token with workspace ID and email."""- # Execute test- RegisterService.revoke_token("workspace-123", "[email protected]", "token-123")-- # Verify results- mock_redis_dependencies.delete.assert_called_once()- call_args = mock_redis_dependencies.delete.call_args- assert "workspace-123" in call_args[0][0]- # The email is hashed, so we check for the hash pattern instead- assert "member_invite_token:" in call_args[0][0]-- def test_revoke_token_without_workspace_and_email(self, mock_redis_dependencies: MagicMock) -> None:- """Test revoking token without workspace ID and email."""- # Execute test- RegisterService.revoke_token("", "", "token-123")-- # Verify results- mock_redis_dependencies.delete.assert_called_once_with("member_invite:token:token-123")-- # ==================== Invitation Validation Tests ====================-- def test_get_invitation_if_token_valid_success(self, sqlite_session: Session) -> None:- """Test successful invitation validation."""- tenant = Tenant(name="Test Workspace")- account = Account(name="Test User", email="[email protected]")- sqlite_session.add_all([tenant, account])- sqlite_session.commit()-- with patch("services.account_service.RegisterService.get_invitation_by_token") as mock_get_invitation_by_token:- invitation_data = {- "account_id": account.id,- "email": "[email protected]",- "workspace_id": tenant.id,- }- mock_get_invitation_by_token.return_value = invitation_data-- result = RegisterService.get_invitation_if_token_valid(- tenant.id, "[email protected]", "token-123", session=sqlite_session- )-- assert result is not None- assert result["account"] is account- assert result["tenant"] is tenant- assert result["data"] == invitation_data-- def test_get_invitation_if_token_valid_no_token_data(- self, unbound_session: Session, mock_redis_dependencies: MagicMock- ) -> None:- """Test invitation validation with no token data."""- # Setup mock- mock_redis_dependencies.get.return_value = None-- # Execute test- result = RegisterService.get_invitation_if_token_valid(- "tenant-456", "[email protected]", "token-123", session=unbound_session- )-- # Verify results- assert result is None-- def test_get_invitation_if_token_valid_tenant_not_found(- self, sqlite_session: Session, mock_redis_dependencies: MagicMock- ) -> None:- """Test invitation validation when tenant is not found."""- # Setup mock Redis data- invitation_data = {- "account_id": "user-123",- "email": "[email protected]",- "workspace_id": "tenant-456",- }- mock_redis_dependencies.get.return_value = json.dumps(invitation_data).encode()-- result = RegisterService.get_invitation_if_token_valid(- "tenant-456", "[email protected]", "token-123", session=sqlite_session- )-- # Verify results- assert result is None-- def test_get_invitation_if_token_valid_account_not_found(- self, sqlite_session: Session, mock_redis_dependencies: MagicMock- ) -> None:- """Test invitation validation when account is not found."""- tenant = Tenant(name="Test Workspace")- sqlite_session.add(tenant)- sqlite_session.commit()-- # Mock Redis data- invitation_data = {- "account_id": "user-123",- "email": "[email protected]",- "workspace_id": tenant.id,- }- mock_redis_dependencies.get.return_value = json.dumps(invitation_data).encode()-- result = RegisterService.get_invitation_if_token_valid(- tenant.id, "[email protected]", "token-123", session=sqlite_session- )-- # Verify results- assert result is None-- def test_get_invitation_if_token_valid_account_id_mismatch(- self, sqlite_session: Session, mock_redis_dependencies: MagicMock- ) -> None:- """Test invitation validation when account ID doesn't match."""- tenant = Tenant(name="Test Workspace")- account = Account(name="Test User", email="[email protected]")- sqlite_session.add_all([tenant, account])- sqlite_session.commit()-- # Mock Redis data with different account ID- invitation_data = {- "account_id": "user-123",- "email": "[email protected]",- "workspace_id": tenant.id,- }- mock_redis_dependencies.get.return_value = json.dumps(invitation_data).encode()-- result = RegisterService.get_invitation_if_token_valid(- tenant.id, "[email protected]", "token-123", session=sqlite_session- )-- # Verify results- assert result is None-- def test_get_invitation_with_case_fallback_returns_initial_match(self, sqlite_session: Session) -> None:- """Fallback helper should return the initial invitation when present."""- invitation = {"workspace_id": "tenant-456"}- with patch(- "services.account_service.RegisterService.get_invitation_if_token_valid", return_value=invitation- ) as mock_get:- result = RegisterService.get_invitation_with_case_fallback(- "tenant-456", "[email protected]", "token-123", session=sqlite_session- )-- assert result == invitation- mock_get.assert_called_once_with(- "tenant-456", "[email protected]", "token-123", session=mock_get.call_args.kwargs["session"]- )-- def test_get_invitation_with_case_fallback_retries_with_lowercase(self, sqlite_session: Session) -> None:- """Fallback helper should retry with lowercase email when needed."""- invitation = {"workspace_id": "tenant-456"}- with patch("services.account_service.RegisterService.get_invitation_if_token_valid") as mock_get:- mock_get.side_effect = [None, invitation]- result = RegisterService.get_invitation_with_case_fallback(- "tenant-456", "[email protected]", "token-123", session=sqlite_session- )-- assert result == invitation- assert mock_get.call_args_list == [- (("tenant-456", "[email protected]", "token-123"), {"session": mock_get.call_args_list[0].kwargs["session"]}),- (("tenant-456", "[email protected]", "token-123"), {"session": mock_get.call_args_list[1].kwargs["session"]}),- ]-- # ==================== Helper Method Tests ====================-- def test_get_invitation_token_key(self) -> None:- """Test the _get_invitation_token_key helper method."""- # Execute test- result = RegisterService._get_invitation_token_key("test-token")-- # Verify results- assert result == "member_invite:token:test-token"-- def test_get_invitation_by_token_with_workspace_and_email(self, mock_redis_dependencies: MagicMock) -> None:- """Test get_invitation_by_token with workspace ID and email."""- # Setup mock- mock_redis_dependencies.get.return_value = b"user-123"-- # Execute test- result = RegisterService.get_invitation_by_token("token-123", "workspace-456", "[email protected]")-- # Verify results- assert result is not None- assert result["account_id"] == "user-123"- assert result["email"] == "[email protected]"- assert result["workspace_id"] == "workspace-456"-- def test_get_invitation_by_token_without_workspace_and_email(self, mock_redis_dependencies: MagicMock) -> None:- """Test get_invitation_by_token without workspace ID and email."""- # Setup mock- invitation_data = {- "account_id": "user-123",- "email": "[email protected]",- "workspace_id": "tenant-456",- }- mock_redis_dependencies.get.return_value = json.dumps(invitation_data).encode()-- # Execute test- result = RegisterService.get_invitation_by_token("token-123")-- # Verify results- assert result is not None- assert result == invitation_data-- def test_get_invitation_by_token_no_data(self, mock_redis_dependencies: MagicMock) -> None:- """Test get_invitation_by_token with no data."""- # Setup mock- mock_redis_dependencies.get.return_value = None-- # Execute test- result = RegisterService.get_invitation_by_token("token-123")-- # Verify results- assert result is None---class TestSessionInjectedGetters:- """Coverage for the session-injected getters used by the openapi- surface. These methods bypass the Flask-scoped ``db.session``- proxy: callers (controllers) pass a session in. The tests use- SQLite-backed rows so query filters and short-circuit behaviour are- exercised without mocking SQLAlchemy's session API.- """-- def _add_tenant_account_join(- self,- sqlite_session: Session,- tenant: Tenant,- account_id: str,- role: TenantAccountRole,- *,- current: bool = False,- ) -> TenantAccountJoin:- tenant_account_join = TenantAccountJoin(- tenant_id=tenant.id,- account_id=account_id,- role=role,- current=current,- )- sqlite_session.add(tenant_account_join)- return tenant_account_join-- def test_get_account_by_id_uses_passed_session_no_side_effects(- self, sqlite_session_factory: sessionmaker[Session]- ) -> None:- """``get_account_by_id`` must be a plain delegation to- ``session.get(Account, ...)`` — no banned-status raise, no- commit (those are the side-effects of ``load_user`` we- explicitly want to skip).- """- with sqlite_session_factory.begin() as arrange_session:- account = Account(name="Alice", email="[email protected]", status=AccountStatus.BANNED)- arrange_session.add(account)- arrange_session.flush()- account_id = account.id-- with sqlite_session_factory() as service_session:- result = AccountService.get_account_by_id(account_id, session=service_session)-- assert result is not None- assert result.id == account_id- assert result.status == AccountStatus.BANNED-- def test_get_account_by_id_returns_none_for_unknown_account(self, sqlite_session: Session) -> None:- assert AccountService.get_account_by_id("missing", session=sqlite_session) is None-- def test_get_account_by_email_returns_scalar_or_none(self, sqlite_session: Session) -> None:- """Plain getter uses case-sensitive equality."""- account = Account(name="Alice", email="[email protected]")- sqlite_session.add(account)- sqlite_session.commit()-- assert AccountService.get_account_by_email("[email protected]", session=sqlite_session) == account- assert AccountService.get_account_by_email("[email protected]", session=sqlite_session) is None- assert AccountService.get_account_by_email("[email protected]", session=sqlite_session) is None-- def test_account_belongs_to_tenant_short_circuits_on_falsy_account_id(self, unbound_session: Session) -> None:- """SSO bearers with no ``account_id`` (and any other falsy id)- must collapse to ``False`` before touching membership storage.- """- assert TenantService.account_belongs_to_tenant(None, "tenant-1", session=unbound_session) is False- assert TenantService.account_belongs_to_tenant("", "tenant-1", session=unbound_session) is False-- def test_account_belongs_to_tenant_true_when_join_row_exists(self, sqlite_session: Session) -> None:- sqlite_session.add(TenantAccountJoin(tenant_id="tenant-1", account_id="user-1", role=TenantAccountRole.NORMAL))- sqlite_session.commit()-- assert TenantService.account_belongs_to_tenant("user-1", "tenant-1", session=sqlite_session) is True- assert TenantService.account_belongs_to_tenant("user-1", "other-tenant", session=sqlite_session) is False-- def test_account_belongs_to_tenant_false_when_no_join(self, sqlite_session: Session) -> None:- assert TenantService.account_belongs_to_tenant("user-1", "tenant-1", session=sqlite_session) is False-- def test_get_workspaces_for_account_uses_session_execute(self, sqlite_session: Session) -> None:- """The list endpoint orders by ``Tenant.created_at``; the helper- returns ``(Tenant, TenantAccountJoin)`` rows in that order.- """- newer_tenant = Tenant(name="Newer Workspace")- older_tenant = Tenant(name="Older Workspace")- sqlite_session.add_all([newer_tenant, older_tenant])- sqlite_session.flush()- newer_tenant.created_at = datetime(2026, 1, 2, 0, 0, 0)- older_tenant.created_at = datetime(2026, 1, 1, 0, 0, 0)- newer_join = self._add_tenant_account_join(sqlite_session, newer_tenant, "user-123", TenantAccountRole.ADMIN)- older_join = self._add_tenant_account_join(sqlite_session, older_tenant, "user-123", TenantAccountRole.NORMAL)- sqlite_session.commit()-- out = TenantService.get_workspaces_for_account("user-123", session=sqlite_session)-- assert [(row[0], row[1]) for row in out] == [(older_tenant, older_join), (newer_tenant, newer_join)]-- def test_get_tenant_by_id_is_plain_session_get(self, sqlite_session_factory: sessionmaker[Session]) -> None:- """``get_tenant_by_id`` must NOT apply a status filter — the- openapi auth pipeline needs to map ``status == ARCHIVE`` to a- 403, distinct from a 404 for "missing".- """- with sqlite_session_factory.begin() as arrange_session:- tenant = Tenant(name="Archived Workspace", status=TenantStatus.ARCHIVE)- arrange_session.add(tenant)- arrange_session.flush()- tenant_id = tenant.id-- with sqlite_session_factory() as service_session:- result = TenantService.get_tenant_by_id(tenant_id, session=service_session)- assert result is not None- assert result.id == tenant_id- assert result.status == TenantStatus.ARCHIVE-- def test_get_tenant_by_id_returns_none_when_missing(self, sqlite_session: Session) -> None:- assert TenantService.get_tenant_by_id("missing", session=sqlite_session) is None-- def test_get_tenants_by_ids_short_circuits_on_empty_input(self, unbound_session: Session) -> None:- """Empty id list must return before touching tenant storage."""- assert TenantService.get_tenants_by_ids([], session=unbound_session) == []-- def test_get_tenants_by_ids_returns_scalars(self, sqlite_session: Session) -> None:- tenant_1 = Tenant(name="Workspace 1")- tenant_2 = Tenant(name="Workspace 2")- tenant_3 = Tenant(name="Workspace 3")- sqlite_session.add_all([tenant_1, tenant_2, tenant_3])- sqlite_session.commit()-- tenants = TenantService.get_tenants_by_ids([tenant_1.id, tenant_3.id], session=sqlite_session)-- assert {tenant.id for tenant in tenants} == {tenant_1.id, tenant_3.id}-- def test_get_tenant_name_returns_scalar_or_none(self, sqlite_session: Session) -> None:- """Single-column lookup: ``session.execute(...).scalar_one_or_none()``- — used by openapi list endpoints to denormalise- ``workspace_name`` onto each row.- """- tenant = Tenant(name="Acme Inc.")- sqlite_session.add(tenant)- sqlite_session.commit()-- assert TenantService.get_tenant_name(tenant.id, session=sqlite_session) == "Acme Inc."- assert TenantService.get_tenant_name("missing", session=sqlite_session) is None-- def test_find_workspace_for_account_returns_first_row_or_none(self, sqlite_session: Session) -> None:- """Per-id read returns ``session.execute(...).first()`` directly;- callers map ``None`` → 404 to avoid leaking workspace IDs across- tenants.- """- tenant = Tenant(name="Workspace")- other_tenant = Tenant(name="Other Workspace")- sqlite_session.add_all([tenant, other_tenant])- sqlite_session.flush()- join = self._add_tenant_account_join(sqlite_session, tenant, "user-123", TenantAccountRole.NORMAL)- self._add_tenant_account_join(sqlite_session, other_tenant, "other-user", TenantAccountRole.NORMAL)- sqlite_session.commit()-- row = TenantService.find_workspace_for_account("user-123", tenant.id, session=sqlite_session)-- assert row is not None- assert row[0] is tenant- assert row[1] is join- assert TenantService.find_workspace_for_account("user-123", other_tenant.id, session=sqlite_session) is None---def test_get_account_by_email_with_case_fallback_uses_lowercase(sqlite_session: Session) -> None:- account = Account(name="Case User", email="[email protected]", normalized_email=normalize_email("[email protected]"))- sqlite_session.add(account)- sqlite_session.commit()-- result = AccountService.get_account_by_email_with_case_fallback("[email protected]", session=sqlite_session)-- assert result is account---def test_get_account_by_email_with_case_fallback_finds_uppercase_row_from_lowercase_input(- sqlite_session: Session,-) -> None:- """Regression test for CUS-1658: an SSO-provisioned account keeps the IdP's original casing- (e.g. `[email protected]`), but the workspace invite flow always looks it up with an- already-lowercased email. The lookup must still find that account.- """- account = Account(name="SSO User", email="[email protected]", normalized_email=normalize_email("[email protected]"))- sqlite_session.add(account)- sqlite_session.commit()-- result = AccountService.get_account_by_email_with_case_fallback("[email protected]", session=sqlite_session)-- assert result is account---def test_get_account_by_email_with_case_fallback_returns_oldest_when_normalized_email_is_duplicated(- sqlite_session: Session,-) -> None:- """normalized_email is indexed but not unique, so installations can already hold equivalent- accounts. The fallback must not raise and must resolve to the same (oldest) account every time.- """- newer = Account(name="Newer", email="[email protected]", normalized_email=normalize_email("[email protected]"))- newer.created_at = datetime(2026, 9, 2)- older = Account(name="Older", email="[email protected]", normalized_email=normalize_email("[email protected]"))- older.created_at = datetime(2026, 9, 1)- sqlite_session.add_all([newer, older])- sqlite_session.commit()-- result = AccountService.get_account_by_email_with_case_fallback("[email protected]", session=sqlite_session)-- assert result is older---class TestIsEmailSendIpLimit:- """The 10-minute first-strike window must actually take effect (#39477)."""-- @pytest.fixture(autouse=True)- def _email_limit_config(self, config_overrides: Callable[..., None]) -> None:- config_overrides(EMAIL_SEND_IP_LIMIT_PER_MINUTE=60)-- def _mock_redis(self, *, minute_count: int, hour_count: int | None, frozen: bool = False) -> MagicMock:- values = {- "email_send_ip_limit_freeze:1.2.3.4": "1" if frozen else None,- "email_send_ip_limit_minute:1.2.3.4": str(minute_count),- "email_send_ip_limit_hour:1.2.3.4": None if hour_count is None else str(hour_count),- }- redis_client = MagicMock()- redis_client.get.side_effect = lambda key: values.get(key)- return redis_client-- def test_frozen_ip_is_limited(self) -> None:- redis_client = self._mock_redis(minute_count=0, hour_count=None, frozen=True)- with patch("services.account_service.redis_client", redis_client):- assert AccountService.is_email_send_ip_limit("1.2.3.4") is True-- def test_first_strike_sets_ten_minute_window(self, config_overrides: Callable[..., None]) -> None:- config_overrides(EMAIL_SEND_IP_LIMIT_PER_MINUTE=1)- redis_client = self._mock_redis(minute_count=999, hour_count=None)- redis_client.set.return_value = True- with (- patch("services.account_service.redis_client", redis_client),- ):- assert AccountService.is_email_send_ip_limit("1.2.3.4") is True-- redis_client.set.assert_called_once_with("email_send_ip_limit_hour:1.2.3.4", 1, ex=60 * 10, nx=True)- # No non-atomic setex/incr/expire may widen or shrink the window.- redis_client.setex.assert_not_called()- redis_client.incr.assert_not_called()- redis_client.expire.assert_not_called()-- def test_first_strike_lost_claim_freezes_immediately(self, config_overrides: Callable[..., None]) -> None:- config_overrides(EMAIL_SEND_IP_LIMIT_PER_MINUTE=1)- redis_client = self._mock_redis(minute_count=999, hour_count=None)- redis_client.set.return_value = None # another worker claimed the strike first- with (- patch("services.account_service.redis_client", redis_client),- ):- assert AccountService.is_email_send_ip_limit("1.2.3.4") is True-- redis_client.setex.assert_called_once_with("email_send_ip_limit_freeze:1.2.3.4", 60 * 60, 1)-- def test_second_strike_inside_window_freezes_for_an_hour(self, config_overrides: Callable[..., None]) -> None:- config_overrides(EMAIL_SEND_IP_LIMIT_PER_MINUTE=1)- redis_client = self._mock_redis(minute_count=999, hour_count=1)- with (- patch("services.account_service.redis_client", redis_client),- ):- assert AccountService.is_email_send_ip_limit("1.2.3.4") is True-- redis_client.setex.assert_called_once_with("email_send_ip_limit_freeze:1.2.3.4", 60 * 60, 1)-- def test_under_limit_not_limited(self) -> None:- redis_client = self._mock_redis(minute_count=0, hour_count=None)- with (- patch("services.account_service.redis_client", redis_client),- ):- assert AccountService.is_email_send_ip_limit("1.2.3.4") is Falsediff --git a/api/tests/unit_tests/services/test_app_dsl_service.py b/api/tests/unit_tests/services/test_app_dsl_service.pyindex 8280c4b41b0..66d2f0067b4 100644--- a/api/tests/unit_tests/services/test_app_dsl_service.py+++ b/api/tests/unit_tests/services/test_app_dsl_service.py@@ -20,8 +20,8 @@ from services.agent.dsl_entities import AgentPackagefrom services.app_dsl_service import AppDslService, PendingDatafrom services.entities.dsl_entities import ImportStatusfrom services.entities.site_dsl import SiteDsl-from services.errors.account import NoPermissionErrorfrom services.errors.app import WorkflowNotFoundError+from services.errors.base import NoPermissionErrorfrom tests.unit_tests.config_override import apply_config_overridesfrom tests.unit_tests.model_factories import make_account, make_app, make_tenant, make_workflowdiff --git a/api/tests/unit_tests/services/test_dataset_service_dataset.py b/api/tests/unit_tests/services/test_dataset_service_dataset.pyindex 28df36f5ced..8ae38e09757 100644--- a/api/tests/unit_tests/services/test_dataset_service_dataset.py+++ b/api/tests/unit_tests/services/test_dataset_service_dataset.py@@ -32,7 +32,7 @@ from services.entities.knowledge_entities.rag_pipeline_entities import (IconInfo,RagPipelineDatasetCreateEntity,)-from services.errors.account import NoPermissionError+from services.errors.base import NoPermissionErrorfrom services.errors.dataset import DatasetNameDuplicateErrorfrom services.knowledge.dataset_service import DatasetCollectionBindingService, DatasetPermissionService, DatasetServicefrom tests.unit_tests.model_factories import make_account, make_dataset, make_tenantdiff --git a/api/tests/unit_tests/services/test_setup_adapters.py b/api/tests/unit_tests/services/test_setup_adapters.pyindex 691a78cf557..5457a578a2b 100644--- a/api/tests/unit_tests/services/test_setup_adapters.py+++ b/api/tests/unit_tests/services/test_setup_adapters.py@@ -1,40 +1,12 @@from contextlib import nullcontext-from unittest.mock import ANY, MagicMock, patch+from unittest.mock import MagicMockimport pytestfrom redis.exceptions import ConnectionError as RedisConnectionErrorfrom redis.exceptions import LockError-from sqlalchemy.orm import Session, sessionmakerfrom extensions.ext_redis import RedisClientWrapper-from services.setup_adapters import RedisSetupLock, RegisterServiceAccountProvisioner-from services.setup_service import SetupInput---def test_provision_delegates_to_register_service_with_managed_session(- sqlite_session_factory: sessionmaker[Session],-) -> None:- provisioner = RegisterServiceAccountProvisioner(session_factory=sqlite_session_factory)- setup = SetupInput(- email="[email protected]",- name="Admin",- password="Passw0rd1",- ip_address="203.0.113.7",- language="en-US",- )-- with patch("services.setup_adapters.RegisterService.setup") as register:- provisioner.provision(setup)-- register.assert_called_once_with(- email="[email protected]",- name="Admin",- password="Passw0rd1",- ip_address="203.0.113.7",- language="en-US",- session=ANY,- )- assert isinstance(register.call_args.kwargs["session"], Session)+from services.setup_adapters import RedisSetupLockdef test_acquire_uses_bounded_distributed_lock() -> None:diff --git a/api/tests/unit_tests/services/test_setup_service.py b/api/tests/unit_tests/services/test_setup_service.pyindex 47ab9bf41bb..d7a4ef4015f 100644--- a/api/tests/unit_tests/services/test_setup_service.py+++ b/api/tests/unit_tests/services/test_setup_service.py@@ -6,15 +6,14 @@ from unittest.mock import Mock, create_autospecimport pytest+from services.account.contracts import SetupInput, SetupStatusfrom services.setup_service import (InitializationValidationRequiredError,SetupAccountProvisioner,SetupAlreadyCompletedError,- SetupInput,SetupLock,SetupService,SetupState,- SetupStatus,)diff --git a/api/tests/unit_tests/services/test_web_authentication_adapters.py b/api/tests/unit_tests/services/test_web_authentication_adapters.pyindex f5570bfb6aa..cdb18e91824 100644--- a/api/tests/unit_tests/services/test_web_authentication_adapters.py+++ b/api/tests/unit_tests/services/test_web_authentication_adapters.py@@ -10,7 +10,7 @@ from enums import WebAppAccessModefrom services.entities.auth_audit_entities import LoginFailureReasonfrom services.entities.authentication_entities import WebAppSessionRecordfrom services.web_authentication_adapters import (- AccountServiceWebAuthenticationSecurityGateway,+ AccountWebAuthenticationSecurityGateway,LoggingWebAuthenticationAuditGateway,PassportWebAppSessionGateway,TokenManagerWebAuthenticationGateway,@@ -221,11 +221,15 @@ def test_generate_code_uses_six_random_digits() -> None:randbelow.assert_called_with(10)-def test_security_gateway_delegates_rate_limits_to_account_service() -> None:- account_service = MagicMock()- account_service.is_email_send_ip_limit.return_value = 1- account_service.is_forgot_password_error_rate_limit.return_value = 0- gateway = AccountServiceWebAuthenticationSecurityGateway(account_service=account_service)+def test_security_gateway_delegates_to_account_security_gateways() -> None:+ password_security = MagicMock()+ login_security = MagicMock()+ password_security.is_ip_limited.return_value = True+ password_security.is_verification_limited.return_value = False+ gateway = AccountWebAuthenticationSecurityGateway(+ password_security=password_security,+ login_security=login_security,+ )assert gateway.is_email_send_ip_limited("203.0.113.1") is Trueassert gateway.is_password_reset_verification_limited("[email protected]") is False@@ -233,11 +237,11 @@ def test_security_gateway_delegates_rate_limits_to_account_service() -> None:gateway.reset_password_reset_verification_failures("[email protected]")gateway.reset_login_failures("[email protected]")- account_service.is_email_send_ip_limit.assert_called_once_with("203.0.113.1")- account_service.is_forgot_password_error_rate_limit.assert_called_once_with("[email protected]")- account_service.add_forgot_password_error_rate_limit.assert_called_once_with("[email protected]")- account_service.reset_forgot_password_error_rate_limit.assert_called_once_with("[email protected]")- account_service.reset_login_error_rate_limit.assert_called_once_with("[email protected]")+ password_security.is_ip_limited.assert_called_once_with("203.0.113.1")+ password_security.is_verification_limited.assert_called_once_with("[email protected]")+ password_security.record_verification_failure.assert_called_once_with("[email protected]")+ password_security.reset_verification_failures.assert_called_once_with("[email protected]")+ login_security.reset_login_failures.assert_called_once_with("[email protected]")@dataclassdiff --git a/api/tests/unit_tests/services/test_workspace_credit_pool.py b/api/tests/unit_tests/services/test_workspace_credit_pool.pydeleted file mode 100644index aef101dcdc4..00000000000--- a/api/tests/unit_tests/services/test_workspace_credit_pool.py+++ /dev/null@@ -1,77 +0,0 @@-from types import SimpleNamespace-from unittest.mock import patch--import pytest-from sqlalchemy.orm import Session--from enums import CloudPlan, DeploymentEdition-from services.credit_pool_service import CreditPoolBalance-from services.workspace_service import WorkspaceService--- ("quota_limit", "quota_used", "remaining_credits", "is_unlimited"),- [(500, 120, 380, False), (-1, 999, -1, True)],-)-def test_get_effective_credit_pool_prefers_available_paid_pool(- quota_limit: int,- quota_used: int,- remaining_credits: int,- is_unlimited: bool,- unbound_session: Session,-) -> None:- paid_pool = CreditPoolBalance(- tenant_id="tenant-1",- pool_type="paid",- quota_limit=quota_limit,- quota_used=quota_used,- )- billing_info = {- "subscription": {"plan": CloudPlan.TEAM},- "next_credit_reset_date": 1775001600,- }- config = SimpleNamespace(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)-- with (- patch("services.workspace_service.dify_config", config),- patch("services.workspace_service.BillingService.get_info", return_value=billing_info),- patch("services.credit_pool_service.CreditPoolService.get_pool", return_value=paid_pool) as get_pool,- ):- result = WorkspaceService.get_effective_credit_pool("tenant-1", session=unbound_session)-- get_pool.assert_called_once_with(tenant_id="tenant-1", pool_type="paid", session=unbound_session)- assert result.pool_type == "paid"- assert result.quota_limit == quota_limit- assert result.quota_used == quota_used- assert result.remaining_credits == remaining_credits- assert result.is_unlimited is is_unlimited- assert result.is_exhausted is False- assert result.next_credit_reset_date == 1775001600---def test_get_effective_credit_pool_exposes_exhausted_trial_pool(unbound_session: Session) -> None:- trial_pool = CreditPoolBalance(- tenant_id="tenant-1",- pool_type="trial",- quota_limit=200,- quota_used=200,- exhausted_at=1772323200,- )- billing_info = {- "subscription": {"plan": CloudPlan.SANDBOX},- }- config = SimpleNamespace(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)-- with (- patch("services.workspace_service.dify_config", config),- patch("services.workspace_service.BillingService.get_info", return_value=billing_info),- patch("services.credit_pool_service.CreditPoolService.get_pool", return_value=trial_pool) as get_pool,- ):- result = WorkspaceService.get_effective_credit_pool("tenant-1", session=unbound_session)-- get_pool.assert_called_once_with(tenant_id="tenant-1", pool_type="trial", session=unbound_session)- assert result.pool_type == "trial"- assert result.remaining_credits == 0- assert result.is_unlimited is False- assert result.is_exhausted is True- assert result.exhausted_at == 1772323200diff --git a/api/tests/unit_tests/services/test_workspace_service.py b/api/tests/unit_tests/services/test_workspace_service.pydeleted file mode 100644index 9dc8789ab67..00000000000--- a/api/tests/unit_tests/services/test_workspace_service.py+++ /dev/null@@ -1,115 +0,0 @@-from types import SimpleNamespace-from unittest.mock import call, patch--from sqlalchemy.orm import Session--from enums import CloudPlan, DeploymentEdition-from models.account import Tenant, TenantAccountJoin, TenantAccountRole-from services.credit_pool_service import CreditPoolBalance-from services.workspace_service import WorkspaceService---def _persist_membership(session: Session, *, role: TenantAccountRole) -> Tenant:- tenant = Tenant(name="Workspace")- session.add_all(- [- tenant,- TenantAccountJoin(tenant_id=tenant.id, account_id="account-1", role=role),- TenantAccountJoin(tenant_id=tenant.id, account_id="decoy-account", role=TenantAccountRole.NORMAL),- TenantAccountJoin(tenant_id="decoy-tenant", account_id="account-1", role=TenantAccountRole.NORMAL),- ]- )- session.commit()- return tenant---def test_get_current_workspace_summary_sandbox_uses_trial_only(sqlite_session: Session) -> None:- tenant = _persist_membership(sqlite_session, role=TenantAccountRole.OWNER)- trial_pool = CreditPoolBalance(- tenant_id=tenant.id,- pool_type="trial",- quota_limit=200,- quota_used=20,- )- billing_info = {- "subscription": {"plan": CloudPlan.SANDBOX},- }- config = SimpleNamespace(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)-- with (- patch("services.workspace_service.dify_config", config),- patch("services.workspace_service.BillingService.get_info", return_value=billing_info) as get_info,- patch("services.credit_pool_service.CreditPoolService.get_pool", return_value=trial_pool) as get_pool,- patch("services.workspace_service.FeatureService.get_features") as get_features,- ):- result = WorkspaceService.get_current_workspace_summary(tenant, "account-1", session=sqlite_session)-- assert result == {- "id": tenant.id,- "name": tenant.name,- "role": "owner",- "plan": CloudPlan.SANDBOX,- "credits": 180,- }- get_info.assert_called_once_with(tenant.id, exclude_vector_space=True)- get_pool.assert_called_once_with(tenant_id=tenant.id, pool_type="trial", session=sqlite_session)- get_features.assert_not_called()---def test_get_current_workspace_summary_falls_back_from_exhausted_paid_pool(sqlite_session: Session) -> None:- tenant = _persist_membership(sqlite_session, role=TenantAccountRole.ADMIN)- paid_pool = CreditPoolBalance(- tenant_id=tenant.id,- pool_type="paid",- quota_limit=500,- quota_used=500,- )- trial_pool = CreditPoolBalance(- tenant_id=tenant.id,- pool_type="trial",- quota_limit=100,- quota_used=40,- )- billing_info = {- "subscription": {"plan": CloudPlan.TEAM},- }- config = SimpleNamespace(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)-- with (- patch("services.workspace_service.dify_config", config),- patch("services.workspace_service.BillingService.get_info", return_value=billing_info),- patch(- "services.credit_pool_service.CreditPoolService.get_pool",- side_effect=[paid_pool, trial_pool],- ) as get_pool,- ):- result = WorkspaceService.get_current_workspace_summary(tenant, "account-1", session=sqlite_session)-- assert result["plan"] == CloudPlan.TEAM- assert result["credits"] == 60- assert get_pool.call_args_list == [- call(tenant_id=tenant.id, pool_type="paid", session=sqlite_session),- call(tenant_id=tenant.id, pool_type="trial", session=sqlite_session),- ]---def test_get_current_workspace_summary_non_cloud_skips_billing_and_credits(sqlite_session: Session) -> None:- tenant = _persist_membership(sqlite_session, role=TenantAccountRole.EDITOR)- config = SimpleNamespace(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)-- with (- patch("services.workspace_service.dify_config", config),- patch("services.workspace_service.BillingService.get_info") as get_info,- patch("services.credit_pool_service.CreditPoolService.get_pool") as get_pool,- ):- result = WorkspaceService.get_current_workspace_summary(tenant, "account-1", session=sqlite_session)-- assert result == {- "id": tenant.id,- "name": tenant.name,- "role": "editor",- "plan": None,- "credits": None,- }- get_info.assert_not_called()- get_pool.assert_not_called()diff --git a/api/tests/unit_tests/services/workspace/__init__.py b/api/tests/unit_tests/services/workspace/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/api/tests/unit_tests/services/workspace/test_gateways.py b/api/tests/unit_tests/services/workspace/test_gateways.pynew file mode 100644index 00000000000..4c35d1af37d--- /dev/null+++ b/api/tests/unit_tests/services/workspace/test_gateways.py@@ -0,0 +1,226 @@+"""Workspace policies and notifications with only external clients replaced."""++from collections.abc import Callable+from unittest.mock import Mock++import pytest++from enums import DeploymentEdition+from extensions.ext_redis import RedisClientWrapper+from services.account.adapters import RedisInvitationTokenStore+from services.enterprise.enterprise_service import WorkspacePermission+from services.entities.feature_entities import FeatureModel, LicenseLimitationModel, LicenseModel, LimitationModel+from services.errors.base import NoPermissionError+from services.errors.workspace import WorkspaceInvitationQuotaError, WorkspaceMemberLicenseQuotaError+from services.workspace import gateways+from tests.unit_tests.account_domain import AccountDomain+++def invitations() -> gateways.WorkspaceInvitationGateway:+ redis = Mock(spec=RedisClientWrapper)+ return gateways.WorkspaceInvitationGateway(tokens=RedisInvitationTokenStore(redis=redis), redis=redis)++[email protected]("allowed", [True, False])+def test_invitation_policy_exposes_domain_errors(+ invitations: gateways.WorkspaceInvitationGateway,+ monkeypatch: pytest.MonkeyPatch,+ config_overrides: Callable[..., None],+ allowed: bool,+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)+ requested: list[str] = []++ def get_permission(workspace_id: str) -> WorkspacePermission:+ requested.append(workspace_id)+ return WorkspacePermission(workspaceId=workspace_id, allowMemberInvite=allowed)++ monkeypatch.setattr(gateways.EnterpriseService.WorkspacePermissionService, "get_permission", get_permission)+ if allowed:+ invitations.ensure_allowed("workspace")+ else:+ with pytest.raises(NoPermissionError, match="Workspace policy prohibits member invitations"):+ invitations.ensure_allowed("workspace")+ assert requested == ["workspace"]++[email protected](("limit", "allowed"), [(0, True), (-1, True), (4, True), (5, True), (3, False)])+def test_cloud_invitation_member_limit(+ invitations: gateways.WorkspaceInvitationGateway,+ monkeypatch: pytest.MonkeyPatch,+ config_overrides: Callable[..., None],+ limit: int,+ allowed: bool,+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)+ # Use the repository's current count, not a potentially stale billing size.+ features = Mock(return_value=FeatureModel(members=LimitationModel(size=99, limit=limit)))+ license_query = Mock(spec=gateways.SystemFeatureService.get_license)+ monkeypatch.setattr(gateways.FeatureService, "get_features", features)+ monkeypatch.setattr(gateways.SystemFeatureService, "get_license", license_query)++ assert invitations.requires_capacity_check+ if allowed:+ invitations.check_capacity("workspace", current_members=2, new_members=2, new_accounts=1)+ else:+ with pytest.raises(WorkspaceInvitationQuotaError) as error:+ invitations.check_capacity("workspace", current_members=2, new_members=2, new_accounts=1)+ assert error.value.seats is False+ features.assert_called_once_with(tenant_id="workspace", exclude_vector_space=True)+ license_query.assert_not_called()+++ ("member_quota", "seat_quota", "new_accounts", "failure"),+ [+ (+ LicenseLimitationModel(enabled=True, size=2, limit=4),+ LicenseLimitationModel(enabled=True, size=9, limit=10),+ 1,+ None,+ ),+ (+ LicenseLimitationModel(enabled=True, size=3, limit=4),+ LicenseLimitationModel(enabled=True, size=9, limit=10),+ 1,+ "members",+ ),+ (LicenseLimitationModel(), LicenseLimitationModel(enabled=True, size=10, limit=10), 1, "seats"),+ (LicenseLimitationModel(), LicenseLimitationModel(enabled=True, size=9, limit=10), 2, "seats"),+ (LicenseLimitationModel(), LicenseLimitationModel(enabled=True, size=8, limit=10), 2, None),+ (LicenseLimitationModel(), LicenseLimitationModel(enabled=True, size=10, limit=10), 0, None),+ (+ LicenseLimitationModel(enabled=True, size=99, limit=0),+ LicenseLimitationModel(enabled=True, size=99, limit=0),+ 2,+ None,+ ),+ (+ LicenseLimitationModel(enabled=False, size=99, limit=1),+ LicenseLimitationModel(enabled=False, size=99, limit=1),+ 2,+ None,+ ),+ ],+ ids=[+ "exact-capacity",+ "workspace-full",+ "seats-full",+ "not-enough-seats-for-batch",+ "exact-seats-for-batch",+ "existing-accounts",+ "unlimited",+ "disabled",+ ],+)+def test_enterprise_invitation_member_and_seat_limits(+ invitations: gateways.WorkspaceInvitationGateway,+ monkeypatch: pytest.MonkeyPatch,+ config_overrides: Callable[..., None],+ member_quota: LicenseLimitationModel,+ seat_quota: LicenseLimitationModel,+ new_accounts: int,+ failure: str | None,+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)+ monkeypatch.setattr(+ gateways.FeatureService, "get_features", Mock(return_value=FeatureModel(workspace_members=member_quota))+ )+ license_query = Mock(return_value=LicenseModel(seats=seat_quota))+ monkeypatch.setattr(gateways.SystemFeatureService, "get_license", license_query)++ assert invitations.requires_capacity_check+ if failure is None:+ invitations.check_capacity("workspace", current_members=2, new_members=2, new_accounts=new_accounts)+ else:+ with pytest.raises(WorkspaceInvitationQuotaError) as error:+ invitations.check_capacity("workspace", current_members=2, new_members=2, new_accounts=new_accounts)+ assert error.value.seats is (failure == "seats")+ assert license_query.call_count == int(new_accounts > 0 and failure != "members")+++def test_community_invitation_does_not_query_quotas(+ invitations: gateways.WorkspaceInvitationGateway,+ monkeypatch: pytest.MonkeyPatch,+ config_overrides: Callable[..., None],+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)+ features = Mock(spec=gateways.FeatureService.get_features)+ license_query = Mock(spec=gateways.SystemFeatureService.get_license)+ monkeypatch.setattr(gateways.FeatureService, "get_features", features)+ monkeypatch.setattr(gateways.SystemFeatureService, "get_license", license_query)++ assert not invitations.requires_capacity_check+ invitations.check_capacity("workspace", current_members=2, new_members=2, new_accounts=1)+ features.assert_not_called()+ license_query.assert_not_called()+++ ("edition", "plan_limit", "license_quota", "error"),+ [+ (DeploymentEdition.CLOUD, 2, LicenseLimitationModel(), WorkspaceInvitationQuotaError),+ (DeploymentEdition.CLOUD, 3, LicenseLimitationModel(), None),+ (DeploymentEdition.CLOUD, 0, LicenseLimitationModel(), None),+ (DeploymentEdition.CLOUD, -1, LicenseLimitationModel(), None),+ (+ DeploymentEdition.ENTERPRISE,+ 2,+ LicenseLimitationModel(enabled=True, size=2, limit=2),+ WorkspaceMemberLicenseQuotaError,+ ),+ (DeploymentEdition.ENTERPRISE, 2, LicenseLimitationModel(enabled=True, size=2, limit=3), None),+ (DeploymentEdition.ENTERPRISE, 2, LicenseLimitationModel(enabled=True, size=2, limit=0), None),+ (DeploymentEdition.COMMUNITY, 2, LicenseLimitationModel(enabled=False, size=2, limit=2), None),+ (+ DeploymentEdition.CLOUD,+ 3,+ LicenseLimitationModel(enabled=True, size=2, limit=2),+ WorkspaceMemberLicenseQuotaError,+ ),+ ],+)+def test_single_invitation_quota_preserves_plan_and_license_limits(+ invitations: gateways.WorkspaceInvitationGateway,+ monkeypatch: pytest.MonkeyPatch,+ config_overrides: Callable[..., None],+ edition: DeploymentEdition,+ plan_limit: int,+ license_quota: LicenseLimitationModel,+ error: type[WorkspaceInvitationQuotaError] | None,+) -> None:+ config_overrides(DEPLOYMENT_EDITION=edition)+ features = FeatureModel(members=LimitationModel(size=2, limit=plan_limit), workspace_members=license_quota)+ requested: list[str] = []++ def get_features(tenant_id: str, *, exclude_vector_space: bool = False) -> FeatureModel:+ requested.append(tenant_id)+ assert exclude_vector_space+ return features++ monkeypatch.setattr(gateways.FeatureService, "get_features", get_features)++ if error is None:+ invitations.check_invitation_quota("workspace")+ else:+ with pytest.raises(error):+ invitations.check_invitation_quota("workspace")+ assert requested == ["workspace"]+++def test_owner_transfer_notifies_both_owners(account_domain: AccountDomain, monkeypatch: pytest.MonkeyPatch) -> None:+ old_owner = account_domain.accounts.create_account("[email protected]", "Old", "en-US")+ new_owner = account_domain.accounts.create_account("[email protected]", "New", "en-US")+ old_notification = Mock(spec=gateways.send_old_owner_transfer_notify_email_task.delay)+ new_notification = Mock(spec=gateways.send_new_owner_transfer_notify_email_task.delay)+ monkeypatch.setattr(gateways.send_old_owner_transfer_notify_email_task, "delay", old_notification)+ monkeypatch.setattr(gateways.send_new_owner_transfer_notify_email_task, "delay", new_notification)++ gateway = gateways.WorkspaceOwnerTransferGateway(redis=Mock(spec=RedisClientWrapper))+ gateway.notify(old_owner=old_owner, new_owner=new_owner, workspace_name="Workspace")++ new_notification.assert_called_once_with(language="en-US", to=new_owner.email, workspace="Workspace")+ old_notification.assert_called_once_with(+ language="en-US", to=old_owner.email, workspace="Workspace", new_owner_email=new_owner.email+ )diff --git a/api/tests/unit_tests/services/workspace/test_member_service.py b/api/tests/unit_tests/services/workspace/test_member_service.pynew file mode 100644index 00000000000..597275b04f0--- /dev/null+++ b/api/tests/unit_tests/services/workspace/test_member_service.py@@ -0,0 +1,936 @@+"""Membership and invitation behavior across the application/persistence boundary."""++from collections.abc import Callable+from contextlib import nullcontext+from unittest.mock import Mock++import pytest+from sqlalchemy import event, select+from sqlalchemy.orm import Session, sessionmaker++from enums import DeploymentEdition+from extensions.ext_redis import RedisClientWrapper+from machinery.context import RequestContext+from models.account import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccountRole+from models.dataset import Dataset+from models.model import App+from services.account.adapters import RedisInvitationTokenStore+from services.account_errors import AccountNotFoundError+from services.enterprise.rbac_service import MemberRolesResponse, Paginated, RBACRole, RBACService+from services.entities.account_entities import AccountSnapshot+from services.entities.feature_entities import FeatureModel, LicenseLimitationModel, LicenseModel+from services.errors.base import NoPermissionError+from services.errors.workspace import (+ AccountAlreadyInTenantError,+ CannotOperateSelfError,+ InvalidOwnerTransferCodeError,+ InvalidOwnerTransferEmailError,+ InvalidOwnerTransferTokenError,+ InvalidWorkspaceMemberRoleError,+ MemberNotInTenantError,+ RoleAlreadyAssignedError,+ WorkspaceAlreadyHasOwnerError,+ WorkspaceInvitationQuotaError,+ WorkspaceNotFoundError,+)+from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureService+from services.workspace.contracts import OwnerTransferToken+from services.workspace.gateways import (+ DeploymentWorkspaceMemberAccessGateway,+ WorkspaceInvitationGateway,+)+from services.workspace.member_service import (+ OwnerTransferGateway,+ WorkspaceInvitationService,+ WorkspaceMemberService,+ WorkspaceOwnerTransferService,+)+from tests.unit_tests.account_domain import AccountDomain+++def members(sqlite_session: Session) -> tuple[str, str, str]:+ owner = Account(name="Owner", email="[email protected]")+ member = Account(name="Member", email="[email protected]")+ tenant = Tenant(name="Workspace")+ sqlite_session.add_all(+ [+ owner,+ member,+ tenant,+ TenantAccountJoin(account_id=owner.id, tenant_id=tenant.id, role=TenantAccountRole.OWNER, current=True),+ TenantAccountJoin(account_id=member.id, tenant_id=tenant.id, role=TenantAccountRole.NORMAL),+ ]+ )+ sqlite_session.commit()+ return tenant.id, owner.id, member.id++[email protected]("existing_member", [True, False])+def test_join_rejects_a_second_owner_without_changing_membership(+ account_domain: AccountDomain, members: tuple[str, str, str], existing_member: bool+) -> None:+ workspace_id, owner_id, member_id = members+ if existing_member:+ account = account_domain.accounts.get_account_by_id(member_id)+ assert account is not None+ else:+ account = account_domain.accounts.create_account("[email protected]", "New owner", "en-US")++ with pytest.raises(WorkspaceAlreadyHasOwnerError, match="Tenant already has an owner"):+ account_domain.members.join_member(+ workspace_id=workspace_id,+ account_id=account.id,+ email=account.email,+ role=TenantAccountRole.OWNER,+ operator_account_id=owner_id,+ )++ assert account_domain.members.get_role(workspace_id, owner_id) == TenantAccountRole.OWNER+ assert account_domain.members.get_role(workspace_id, account.id) == (+ TenantAccountRole.NORMAL if existing_member else None+ )+ account_domain.access.membership_changed.assert_not_called()+++ ("status", "other_workspace", "deleted"),+ [("pending", False, True), ("pending", True, False), ("active", False, False)],+)+def test_removal_deletes_only_orphaned_pending_accounts(+ account_domain: AccountDomain,+ sqlite_session: Session,+ members: tuple[str, str, str],+ status: str,+ other_workspace: bool,+ deleted: bool,+) -> None:+ workspace_id, owner_id, member_id = members+ member = sqlite_session.get(Account, member_id)+ assert member is not None+ member.status = AccountStatus(status)+ if other_workspace:+ tenant = Tenant(name="Other")+ sqlite_session.add_all(+ [tenant, TenantAccountJoin(account_id=member_id, tenant_id=tenant.id, role=TenantAccountRole.NORMAL)]+ )+ sqlite_session.commit()+ sqlite_session.expunge_all()+ account_domain.members.remove(workspace_id, member_id, owner_id)+ assert (sqlite_session.get(Account, member_id) is None) == deleted+ assert account_domain.members.get_role(workspace_id, member_id) is None+ account_domain.access.member_removed.assert_called_once()+ assert account_domain.access.member_removed.call_args.args[1].account_deleted == deleted++[email protected]("action", ["add", "remove", "update"])+def test_self_operations_and_non_administrators_are_denied(+ account_domain: AccountDomain, members: tuple[str, str, str], action: str+) -> None:+ workspace_id, owner_id, member_id = members+ with pytest.raises(CannotOperateSelfError):+ account_domain.members.check_permission(workspace_id, owner_id, owner_id, action)+ with pytest.raises(NoPermissionError):+ account_domain.members.check_permission(workspace_id, member_id, owner_id, action)+++def test_owner_transfer_demotes_previous_owner(account_domain: AccountDomain, members: tuple[str, str, str]) -> None:+ workspace_id, owner_id, member_id = members+ account_domain.members.update_role(workspace_id, member_id, "owner", owner_id)+ assert account_domain.members.get_role(workspace_id, owner_id) == TenantAccountRole.NORMAL+ assert account_domain.members.get_role(workspace_id, member_id) == TenantAccountRole.OWNER++[email protected]("new_role", ["normal", "owner"])+def test_admin_cannot_change_owner_or_promote_owner(+ account_domain: AccountDomain, members: tuple[str, str, str], sqlite_session: Session, new_role: str+) -> None:+ workspace_id, owner_id, member_id = members+ membership = sqlite_session.scalar(select(TenantAccountJoin).where(TenantAccountJoin.account_id == member_id))+ assert membership is not None+ membership.role = TenantAccountRole.ADMIN+ sqlite_session.commit()+ with pytest.raises(NoPermissionError):+ account_domain.members.update_role(workspace_id, owner_id, new_role, member_id)+++def test_unchanged_role_does_not_sync(account_domain: AccountDomain, members: tuple[str, str, str]) -> None:+ workspace_id, owner_id, member_id = members+ with pytest.raises(RoleAlreadyAssignedError):+ account_domain.members.update_role(workspace_id, member_id, "normal", owner_id)+ account_domain.access.change_role.assert_not_called()++[email protected]("role", ["invalid", "dataset_operator"])+def test_role_policy_prevents_persistence_and_rbac_changes(+ account_domain: AccountDomain,+ sqlite_session_factory: sessionmaker[Session],+ members: tuple[str, str, str],+ config_overrides: Callable[..., None],+ role: str,+) -> None:+ config_overrides(DATASET_OPERATOR_ENABLED=False)+ account_domain.access.ensure_role_enabled.side_effect = DeploymentWorkspaceMemberAccessGateway(+ session_factory=sqlite_session_factory+ ).ensure_role_enabled+ workspace_id, owner_id, member_id = members++ with pytest.raises(InvalidWorkspaceMemberRoleError):+ account_domain.members.update_role(workspace_id, member_id, role, owner_id)++ assert account_domain.members.get_role(workspace_id, member_id) == TenantAccountRole.NORMAL+ account_domain.access.change_role.assert_not_called()++[email protected]("operation", ["remove", "update_role"])[email protected]("account_exists", [True, False])+def test_member_operations_distinguish_missing_account_from_missing_membership(+ account_domain: AccountDomain, members: tuple[str, str, str], operation: str, account_exists: bool+) -> None:+ workspace_id, owner_id, _ = members+ account_id = "00000000-0000-0000-0000-000000000000"+ if account_exists:+ account_id = account_domain.accounts.create_account("[email protected]", "Outsider", "en-US").id++ error = MemberNotInTenantError if account_exists else AccountNotFoundError+ if operation == "remove":+ with pytest.raises(error):+ account_domain.members.remove(workspace_id, account_id, owner_id)+ else:+ with pytest.raises(error):+ account_domain.members.update_role(workspace_id, account_id, "editor", owner_id)++ account_domain.access.member_removed.assert_not_called()+ account_domain.access.change_role.assert_not_called()+++ ("permission", "owner", "allowed"), [(True, False, True), (False, False, False), (True, True, False)]+)+def test_rbac_member_removal_uses_permissions_and_owner_protection(+ account_domain: AccountDomain, members: tuple[str, str, str], permission: bool, owner: bool, allowed: bool+) -> None:+ workspace_id, owner_id, member_id = members+ account_domain.access.rbac_enabled = True+ account_domain.access.permission_keys.return_value = {"workspace.member.manage"} if permission else set()+ account_domain.access.is_owner.return_value = owner+ account_domain.access.owner_id.return_value = owner_id+ if allowed:+ account_domain.members.remove(workspace_id, member_id, owner_id)+ assert account_domain.members.get_role(workspace_id, member_id) is None+ else:+ with pytest.raises(NoPermissionError):+ account_domain.members.remove(workspace_id, member_id, owner_id)+++def test_new_invitation_normalizes_email_and_sets_current_workspace(+ account_domain: AccountDomain, members: tuple[str, str, str]+) -> None:+ workspace_id, owner_id, _ = members+ result = account_domain.invitations.invite(+ RequestContext("request", None, owner_id, workspace_id), "[email protected]", "en-US", "editor"+ )+ assert result.token == "invitation-token"+ assert result.email == "[email protected]"+ assert result.workspace_id == workspace_id+ assert result.role == "editor"+ invitee = account_domain.repository.find_by_email("[email protected]")+ assert invitee is not None+ assert result.account_id == invitee.id+ assert invitee.status == "pending"+ assert account_domain.members.get_role(workspace_id, invitee.id) == TenantAccountRole.EDITOR+ membership = account_domain.workspaces.find_membership(invitee.id, workspace_id)+ assert membership is not None+ assert membership.current+ invitation = account_domain.delivery.create.call_args.args[0]+ assert invitation.requires_setup is True+ assert invitation.email == "[email protected]"+++def test_active_invitee_must_accept_before_joining(+ account_domain: AccountDomain, members: tuple[str, str, str]+) -> None:+ workspace_id, owner_id, _ = members+ account = account_domain.accounts.create_account("[email protected]", "New", "en-US")+ account_domain.invitations.invite(RequestContext("request", None, owner_id, workspace_id), account.email, None)+ assert account_domain.members.get_role(workspace_id, account.id) is None+ assert account_domain.delivery.create.call_args.args[0].requires_setup is False+++def test_pending_member_can_be_reinvited(+ account_domain: AccountDomain, members: tuple[str, str, str], sqlite_session: Session+) -> None:+ workspace_id, owner_id, member_id = members+ account = sqlite_session.get(Account, member_id)+ assert account is not None+ account.status = AccountStatus.PENDING+ sqlite_session.commit()+ account_domain.invitations.invite(RequestContext("request", None, owner_id, workspace_id), account.email, None)+ assert account_domain.delivery.create.call_args.args[0].requires_setup is True+++def test_active_member_is_reported_without_sending_invitation(+ account_domain: AccountDomain, members: tuple[str, str, str]+) -> None:+ workspace_id, owner_id, _ = members+ with pytest.raises(AccountAlreadyInTenantError):+ account_domain.invitations.invite(+ RequestContext("request", None, owner_id, workspace_id), "[email protected]", None+ )+ account_domain.delivery.send.assert_not_called()+++def test_removal_transfers_maintainers_only_in_the_target_workspace(+ account_domain: AccountDomain, members: tuple[str, str, str], sqlite_session: Session+) -> None:+ workspace_id, owner_id, member_id = members+ other = Tenant(name="Other workspace")+ sqlite_session.add(other)+ apps = [+ App(+ tenant_id=tenant_id,+ name="App",+ mode="chat",+ maintainer=member_id,+ enable_site=True,+ enable_api=True,+ max_active_requests=0,+ )+ for tenant_id in (workspace_id, other.id)+ ]+ datasets = [+ Dataset(tenant_id=tenant_id, name="Dataset", created_by=member_id, maintainer=member_id)+ for tenant_id in (workspace_id, other.id)+ ]+ sqlite_session.add_all([*apps, *datasets])+ sqlite_session.commit()++ account_domain.members.remove(workspace_id, member_id, owner_id)++ sqlite_session.expire_all()+ assert [app.maintainer for app in apps] == [owner_id, member_id]+ assert [dataset.maintainer for dataset in datasets] == [owner_id, member_id]+++def test_community_invitation_continues_after_a_historical_duplicate_email(+ account_domain: AccountDomain, members: tuple[str, str, str], sqlite_session: Session+) -> None:+ workspace_id, owner_id, _ = members+ sqlite_session.add_all(+ [+ Account(name="First", email="[email protected]"),+ Account(name="Second", email="[email protected]"),+ ]+ )+ sqlite_session.commit()+ account_domain.delivery.acquire.return_value = nullcontext()++ results = account_domain.invitations.invite_many(+ RequestContext("request", None, owner_id, workspace_id),+ emails=["[email protected]", "[email protected]"],+ language=None,+ role="normal",+ )++ assert [result.status for result in results] == ["failed", "success"]+ account_domain.delivery.check_capacity.assert_not_called()+ account_domain.delivery.send.assert_called_once()+ assert account_domain.repository.find_by_email("[email protected]") is not None+++def test_bulk_invitation_counts_new_accounts_and_members_before_writing(+ account_domain: AccountDomain,+ members: tuple[str, str, str],+ monkeypatch: pytest.MonkeyPatch,+ config_overrides: Callable[..., None],+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)+ monkeypatch.setattr(FeatureService, "get_features", Mock(return_value=FeatureModel()))+ monkeypatch.setattr(+ SystemFeatureService,+ "get_license",+ Mock(return_value=LicenseModel(seats=LicenseLimitationModel(enabled=True, size=3, limit=3))),+ )+ redis = Mock(spec=RedisClientWrapper)+ gateway = WorkspaceInvitationGateway(tokens=RedisInvitationTokenStore(redis=redis), redis=redis)+ workspace_id, owner_id, _ = members+ account_domain.accounts.create_account("[email protected]", "Outside", "en-US")+ account_domain.delivery.acquire.return_value = nullcontext()+ account_domain.delivery.check_capacity.side_effect = gateway.check_capacity+ account_domain.delivery.requires_capacity_check = True++ with pytest.raises(WorkspaceInvitationQuotaError) as error:+ account_domain.invitations.invite_many(+ RequestContext("request", None, owner_id, workspace_id),+ language=None,+ role="normal",+ )++ assert error.value.seats is True+ account_domain.delivery.check_capacity.assert_called_once_with(+ workspace_id, current_members=2, new_members=2, new_accounts=1+ )+ assert account_domain.repository.find_by_email("[email protected]") is None+ account_domain.delivery.create.assert_not_called()+++def test_bulk_invitation_retains_partial_results_under_workspace_lock(+ account_domain: AccountDomain, members: tuple[str, str, str]+) -> None:+ workspace_id, owner_id, _ = members+ account_domain.delivery.acquire.return_value = nullcontext()+ account_domain.delivery.send.side_effect = [None, RuntimeError("Mail unavailable")]++ results = account_domain.invitations.invite_many(+ RequestContext("request", None, owner_id, workspace_id),+ language=None,+ role="normal",+ )++ assert [(result.email, result.status) for result in results] == [+ ("[email protected]", "success"),+ ("[email protected]", "already_member"),+ ("[email protected]", "failed"),+ ]+ assert results[-1].message == "Mail unavailable"+ account_domain.delivery.acquire.assert_called_once_with(workspace_id)+++def owner_transfer(account_domain: AccountDomain) -> tuple[WorkspaceOwnerTransferService, Mock]:+ challenges = Mock(spec=OwnerTransferGateway)+ challenges.is_ip_limited.return_value = False+ challenges.is_verification_limited.return_value = False+ challenges.read_token.return_value = OwnerTransferToken("[email protected]", "123456")+ challenges.issue_token.return_value = "promoted-token"+ return WorkspaceOwnerTransferService(+ accounts=account_domain.repository,+ workspaces=account_domain.workspaces,+ members=account_domain.members,+ challenges=challenges,+ ), challenges+++ ("challenge", "code", "error"),+ [+ (None, "123456", InvalidOwnerTransferTokenError),+ (OwnerTransferToken("[email protected]", "123456"), "123456", InvalidOwnerTransferEmailError),+ (OwnerTransferToken("[email protected]", "123456"), "000000", InvalidOwnerTransferCodeError),+ ],+)+def test_owner_verification_failure_preserves_challenge(+ owner_transfer: tuple[WorkspaceOwnerTransferService, Mock],+ members: tuple[str, str, str],+ challenge: OwnerTransferToken | None,+ code: str,+ error: type[Exception],+) -> None:+ service, challenges = owner_transfer+ workspace_id, owner_id, _ = members+ challenges.read_token.return_value = challenge+ with pytest.raises(error):+ service.verify_code(RequestContext("request", None, owner_id, workspace_id), token="challenge", code=code)+ challenges.revoke_token.assert_not_called()+ challenges.issue_token.assert_not_called()+ if error is InvalidOwnerTransferCodeError:+ challenges.record_verification_failure.assert_called_once_with("[email protected]")+++def test_owner_verification_promotes_token_and_clears_failure_count(+ owner_transfer: tuple[WorkspaceOwnerTransferService, Mock],+ members: tuple[str, str, str],+) -> None:+ service, challenges = owner_transfer+ workspace_id, owner_id, _ = members+ result = service.verify_code(+ RequestContext("request", None, owner_id, workspace_id), token="challenge", code="123456"+ )+ assert result == ("[email protected]", "promoted-token")+ challenges.revoke_token.assert_called_once_with("challenge")+ challenges.reset_verification_failures.assert_called_once_with("[email protected]")+++def test_owner_transfer_commits_roles_before_notification(+ owner_transfer: tuple[WorkspaceOwnerTransferService, Mock],+ members: tuple[str, str, str],+ account_domain: AccountDomain,+) -> None:+ service, challenges = owner_transfer+ workspace_id, owner_id, member_id = members++ def notify(*, old_owner: AccountSnapshot, new_owner: AccountSnapshot, workspace_name: str) -> None:+ assert (old_owner.id, new_owner.id, workspace_name) == (owner_id, member_id, "Workspace")+ assert account_domain.members.get_role(workspace_id, owner_id) == TenantAccountRole.NORMAL+ assert account_domain.members.get_role(workspace_id, member_id) == TenantAccountRole.OWNER++ challenges.notify.side_effect = notify+ service.transfer(RequestContext("request", None, owner_id, workspace_id), member_id=member_id, token="challenge")+ challenges.notify.assert_called_once()+++def test_owner_transfer_rejects_accounts_outside_workspace(+ owner_transfer: tuple[WorkspaceOwnerTransferService, Mock],+ members: tuple[str, str, str],+ account_domain: AccountDomain,+) -> None:+ service, challenges = owner_transfer+ workspace_id, owner_id, _ = members+ outside = account_domain.accounts.create_account("[email protected]", "Outside", "en-US")+ with pytest.raises(MemberNotInTenantError):+ service.transfer(+ RequestContext("request", None, owner_id, workspace_id), member_id=outside.id, token="challenge"+ )+ assert account_domain.members.get_role(workspace_id, owner_id) == TenantAccountRole.OWNER+ challenges.notify.assert_not_called()++[email protected]("operation", ["send_code", "transfer"])+def test_owner_transfer_reports_missing_workspace(+ owner_transfer: tuple[WorkspaceOwnerTransferService, Mock],+ members: tuple[str, str, str],+ account_domain: AccountDomain,+ monkeypatch: pytest.MonkeyPatch,+ operation: str,+) -> None:+ service, challenges = owner_transfer+ workspace_id, owner_id, member_id = members+ monkeypatch.setattr(account_domain.workspaces, "get", lambda _workspace_id: None)+ context = RequestContext("request", None, owner_id, workspace_id)+ if operation == "send_code":+ with pytest.raises(WorkspaceNotFoundError):+ service.send_code(context, ip_address="127.0.0.1", language=None)+ else:+ with pytest.raises(WorkspaceNotFoundError):+ service.transfer(context, member_id=member_id, token="challenge")+ challenges.send_confirmation.assert_not_called()+ challenges.notify.assert_not_called()+ assert account_domain.members.get_role(workspace_id, owner_id) == TenantAccountRole.OWNER+++def test_rbac_transfer_failure_leaves_local_owner_unchanged(+ account_domain: AccountDomain,+ members: tuple[str, str, str],+) -> None:+ workspace_id, owner_id, member_id = members+ account_domain.access.rbac_enabled = True+ account_domain.access.is_owner.side_effect = lambda _workspace_id, _actor_id, member_id: member_id == owner_id+ account_domain.access.transfer_owner.side_effect = RuntimeError("RBAC unavailable")+ with pytest.raises(RuntimeError, match="RBAC unavailable"):+ account_domain.members.update_role(workspace_id, member_id, "owner", owner_id)+ assert account_domain.members.get_role(workspace_id, owner_id) == TenantAccountRole.OWNER+ assert account_domain.members.get_role(workspace_id, member_id) == TenantAccountRole.NORMAL+++def rbac_access(+ sqlite_session_factory: sessionmaker[Session],+ monkeypatch: pytest.MonkeyPatch,+ config_overrides: Callable[..., None],+ members: tuple[str, str, str],+) -> tuple[DeploymentWorkspaceMemberAccessGateway, Mock]:+ config_overrides(RBAC_ENABLED=True, DATASET_OPERATOR_ENABLED=True)+ gateway = DeploymentWorkspaceMemberAccessGateway(session_factory=sqlite_session_factory)+ roles = [+ RBACRole(id=f"role-{tag}", name=tag, type="", category="global_system_default", role_tag=tag, is_builtin=True)+ for tag in [*(role.value for role in TenantAccountRole), "no_access"]+ ]+ _, owner_id, _ = members+ roles_by_tag = {role.role_tag: role for role in roles}++ def get_roles(+ tenant_id: str, account_id: str | None, member_account_id: str, *, session: Session+ ) -> MemberRolesResponse:+ del tenant_id, account_id, session+ tag = "owner" if member_account_id == owner_id else "normal"+ return MemberRolesResponse(account_id=member_account_id, roles=[roles_by_tag[tag]])++ monkeypatch.setattr(RBACService.Roles, "list", Mock(return_value=Paginated[RBACRole](data=roles)))+ monkeypatch.setattr(RBACService.MemberRoles, "get", get_roles)+ monkeypatch.setattr(gateway, "permission_keys", lambda _workspace_id, _actor_id: {"workspace.role.manage"})+ replace = Mock(spec=RBACService.MemberRoles.replace)+ monkeypatch.setattr(RBACService.MemberRoles, "replace", replace)+ return gateway, replace+++ ("status", "already_joined"),+ [+ (None, False),+ (AccountStatus.PENDING, False),+ (AccountStatus.PENDING, True),+ (AccountStatus.ACTIVE, False),+ (AccountStatus.ACTIVE, True),+ ],+ ids=["new-account", "pending-account", "pending-member", "active-account", "active-member"],+)+def test_rbac_invitation_assigns_requested_role(+ account_domain: AccountDomain,+ members: tuple[str, str, str],+ sqlite_session: Session,+ rbac_access: tuple[DeploymentWorkspaceMemberAccessGateway, Mock],+ monkeypatch: pytest.MonkeyPatch,+ status: AccountStatus | None,+ already_joined: bool,+) -> None:+ from tasks.initialize_created_app_rbac_access_task import sync_joined_workspace_member_rbac_access_task++ workspace_id, owner_id, _ = members+ email = "[email protected]"+ if status is not None:+ account = Account(name="Invited", email=email, status=status)+ sqlite_session.add(account)+ if already_joined:+ sqlite_session.add(+ TenantAccountJoin(tenant_id=workspace_id, account_id=account.id, role=TenantAccountRole.NORMAL)+ )+ sqlite_session.commit()+ access, replace = rbac_access+ monkeypatch.setattr(access, "permission_keys", lambda _workspace, _actor: {"workspace.member.manage"})+ sync = Mock(spec=sync_joined_workspace_member_rbac_access_task.delay)+ monkeypatch.setattr(sync_joined_workspace_member_rbac_access_task, "delay", sync)+ member_service = WorkspaceMemberService(+ workspaces=account_domain.workspaces, accounts=account_domain.repository, access=access+ )+ invitations = WorkspaceInvitationService(+ accounts=account_domain.accounts,+ workspaces=account_domain.workspaces,+ members=member_service,+ invitations=account_domain.delivery,+ )+ account_domain.delivery.acquire.return_value = nullcontext()++ results = invitations.invite_many(+ RequestContext("request", None, owner_id, workspace_id),+ emails=[email],+ language="en-US",+ role="custom-role-id",+ )++ invited = account_domain.repository.find_by_email(email)+ assert invited is not None+ assert member_service.get_role(workspace_id, invited.id) == TenantAccountRole.NORMAL+ if status == AccountStatus.ACTIVE and already_joined:+ replace.assert_not_called()+ else:+ assignments = [item.kwargs for item in replace.call_args_list if item.kwargs["tenant_id"] == workspace_id]+ assert len(assignments) == 1+ assert assignments[0]["account_id"] == owner_id+ assert assignments[0]["member_account_id"] == invited.id+ assert assignments[0]["role_ids"] == ["custom-role-id"]+ if status is None:+ # Registration also provisions the invitee's own workspace.+ assert replace.call_count == 2+ personal_workspace = replace.call_args_list[0].kwargs+ assert personal_workspace["tenant_id"] != workspace_id+ assert personal_workspace["member_account_id"] == invited.id+ assert personal_workspace["role_ids"] == ["role-owner"]+ else:+ replace.assert_called_once()+ if status == AccountStatus.ACTIVE:+ assert results[0].status == "already_member"+ account_domain.delivery.create.assert_not_called()+ account_domain.delivery.send.assert_not_called()+ else:+ assert results[0].status == "success"+ assert invited.status == "pending"+ invitation = account_domain.delivery.create.call_args.args[0]+ assert invitation.account_id == invited.id+ assert invitation.role == "custom-role-id"+ assert invitation.requires_setup is True+ account_domain.delivery.send.assert_called_once_with(+ language="en-US", email=email, token="invitation-token", inviter_name="Owner", workspace_name="Workspace"+ )+ assert sync.call_count == int(status == AccountStatus.ACTIVE and not already_joined)+++ "operator_role",+ [TenantAccountRole.NORMAL, TenantAccountRole.EDITOR, TenantAccountRole.ADMIN, TenantAccountRole.DATASET_OPERATOR],+)+ "new_role",+ [TenantAccountRole.NORMAL, TenantAccountRole.EDITOR, TenantAccountRole.ADMIN, TenantAccountRole.DATASET_OPERATOR],+)+def test_rbac_role_managers_cannot_demote_owner(+ account_domain: AccountDomain,+ members: tuple[str, str, str],+ sqlite_session: Session,+ rbac_access: tuple[DeploymentWorkspaceMemberAccessGateway, Mock],+ operator_role: TenantAccountRole,+ new_role: TenantAccountRole,+) -> None:+ workspace_id, owner_id, operator_id = members+ membership = sqlite_session.scalar(select(TenantAccountJoin).where(TenantAccountJoin.account_id == operator_id))+ assert membership is not None+ membership.role = operator_role+ sqlite_session.commit()+ gateway, replace = rbac_access+ service = WorkspaceMemberService(+ workspaces=account_domain.workspaces, accounts=account_domain.repository, access=gateway+ )++ with pytest.raises(NoPermissionError):+ service.update_role(workspace_id, owner_id, new_role.value, operator_id)++ replace.assert_not_called()+ assert service.get_role(workspace_id, owner_id) == TenantAccountRole.OWNER+ assert service.get_role(workspace_id, operator_id) == operator_role+++ "operator_role",+ [TenantAccountRole.NORMAL, TenantAccountRole.EDITOR, TenantAccountRole.ADMIN, TenantAccountRole.DATASET_OPERATOR],+)+def test_rbac_role_managers_cannot_transfer_ownership(+ account_domain: AccountDomain,+ members: tuple[str, str, str],+ sqlite_session: Session,+ operator_role: TenantAccountRole,+) -> None:+ workspace_id, owner_id, operator_id = members+ membership = sqlite_session.scalar(select(TenantAccountJoin).where(TenantAccountJoin.account_id == operator_id))+ assert membership is not None+ membership.role = operator_role+ target = Account(name="Target", email="[email protected]")+ sqlite_session.add_all(+ [target, TenantAccountJoin(tenant_id=workspace_id, account_id=target.id, role=TenantAccountRole.NORMAL)]+ )+ sqlite_session.commit()+ account_domain.access.rbac_enabled = True+ account_domain.access.permission_keys.return_value = {"workspace.role.manage"}++ with pytest.raises(NoPermissionError):+ account_domain.members.update_role(workspace_id, target.id, "owner", operator_id)++ account_domain.access.transfer_owner.assert_not_called()+ account_domain.access.change_role.assert_not_called()+ assert account_domain.members.get_role(workspace_id, owner_id) == TenantAccountRole.OWNER+ assert account_domain.members.get_role(workspace_id, target.id) == TenantAccountRole.NORMAL+++def test_rbac_normal_role_manager_can_update_another_non_owner(+ account_domain: AccountDomain,+ members: tuple[str, str, str],+ sqlite_session: Session,+ rbac_access: tuple[DeploymentWorkspaceMemberAccessGateway, Mock],+) -> None:+ workspace_id, owner_id, operator_id = members+ target = Account(name="Target", email="[email protected]")+ sqlite_session.add_all(+ [target, TenantAccountJoin(tenant_id=workspace_id, account_id=target.id, role=TenantAccountRole.NORMAL)]+ )+ sqlite_session.commit()+ gateway, replace = rbac_access+ service = WorkspaceMemberService(+ workspaces=account_domain.workspaces, accounts=account_domain.repository, access=gateway+ )++ service.update_role(workspace_id, target.id, "editor", operator_id)++ replace.assert_called_once()+ assert replace.call_args.kwargs["member_account_id"] == target.id+ assert replace.call_args.kwargs["role_ids"] == ["role-editor"]+ assert service.get_role(workspace_id, target.id) == TenantAccountRole.EDITOR+ assert service.get_role(workspace_id, owner_id) == TenantAccountRole.OWNER+++ "role",+ [TenantAccountRole.ADMIN, TenantAccountRole.EDITOR, TenantAccountRole.NORMAL, TenantAccountRole.DATASET_OPERATOR],+)[email protected]("remote_fails", [False, True])+def test_rbac_role_update_assigns_requested_role_and_synchronizes_membership(+ account_domain: AccountDomain,+ members: tuple[str, str, str],+ sqlite_session: Session,+ rbac_access: tuple[DeploymentWorkspaceMemberAccessGateway, Mock],+ role: TenantAccountRole,+ remote_fails: bool,+) -> None:+ workspace_id, owner_id, member_id = members+ previous = TenantAccountRole.EDITOR if role == TenantAccountRole.NORMAL else TenantAccountRole.NORMAL+ membership = sqlite_session.scalar(select(TenantAccountJoin).where(TenantAccountJoin.account_id == member_id))+ assert membership is not None+ membership.role = previous+ sqlite_session.commit()+ gateway, replace = rbac_access+ service = WorkspaceMemberService(+ workspaces=account_domain.workspaces, accounts=account_domain.repository, access=gateway+ )+ if remote_fails:+ replace.side_effect = RuntimeError("RBAC unavailable")+ with pytest.raises(RuntimeError, match="RBAC unavailable"):+ service.update_role(workspace_id, member_id, role.value, owner_id)+ else:+ service.update_role(workspace_id, member_id, role.value, owner_id)++ replace.assert_called_once()+ assert replace.call_args.kwargs["role_ids"] == [f"role-{role.value}"]+ assert replace.call_args.kwargs["member_account_id"] == member_id+ assert service.get_role(workspace_id, member_id) == (previous if remote_fails else role)+ assert service.get_role(workspace_id, owner_id) == TenantAccountRole.OWNER+++def test_rbac_owner_transfer_preserves_other_roles_and_updates_both_memberships(+ account_domain: AccountDomain,+ members: tuple[str, str, str],+ rbac_access: tuple[DeploymentWorkspaceMemberAccessGateway, Mock],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ workspace_id, owner_id, member_id = members+ gateway, replace = rbac_access+ monkeypatch.setattr(gateway, "owner_id", lambda _workspace_id, _actor_id: owner_id)+ current_roles = MemberRolesResponse(+ account_id=owner_id,+ roles=[+ RBACRole(+ id="role-owner",+ name="Owner",+ type="",+ category="global_system_default",+ role_tag="owner",+ is_builtin=True,+ ),+ RBACRole(id="custom", name="Custom", type=""),+ ],+ )++ def get_roles(+ tenant_id: str, account_id: str | None, member_account_id: str, *, session: Session+ ) -> MemberRolesResponse:+ del tenant_id, account_id, session+ return current_roles if member_account_id == owner_id else MemberRolesResponse(account_id=member_account_id)++ monkeypatch.setattr(RBACService.MemberRoles, "get", get_roles)+ service = WorkspaceMemberService(+ workspaces=account_domain.workspaces, accounts=account_domain.repository, access=gateway+ )++ service.update_role(workspace_id, member_id, "owner", owner_id)++ assert [(call.kwargs["member_account_id"], call.kwargs["role_ids"]) for call in replace.call_args_list] == [+ (owner_id, ["custom"]),+ (member_id, ["role-owner"]),+ ]+ assert service.get_role(workspace_id, owner_id) == TenantAccountRole.NORMAL+ assert service.get_role(workspace_id, member_id) == TenantAccountRole.OWNER++[email protected]("operation", ["demote_new_owner", "transfer_to_another_member"])+def test_rbac_owner_is_protected_after_local_transfer_commit_fails(+ account_domain: AccountDomain,+ members: tuple[str, str, str],+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+ rbac_access: tuple[DeploymentWorkspaceMemberAccessGateway, Mock],+ monkeypatch: pytest.MonkeyPatch,+ operation: str,+) -> None:+ workspace_id, old_owner_id, new_owner_id = members+ third_member = Account(name="Third", email="[email protected]")+ sqlite_session.add_all(+ [+ third_member,+ TenantAccountJoin(tenant_id=workspace_id, account_id=third_member.id, role=TenantAccountRole.NORMAL),+ ]+ )+ sqlite_session.commit()+ gateway, replace = rbac_access+ owner_role = RBACRole(+ id="role-owner", name="Owner", type="", category="global_system_default", role_tag="owner", is_builtin=True+ )+ custom_role = RBACRole(id="custom-manager", name="Role manager", type="")+ remote_roles = {old_owner_id: [owner_role, custom_role], new_owner_id: [], third_member.id: []}+ roles_by_id = {role.id: role for role in [owner_role, custom_role]}++ def get_roles(+ tenant_id: str, account_id: str | None, member_account_id: str, *, session: Session+ ) -> MemberRolesResponse:+ del tenant_id, account_id, session+ return MemberRolesResponse(account_id=member_account_id, roles=remote_roles[member_account_id])++ def replace_roles(+ *, tenant_id: str, account_id: str, member_account_id: str, role_ids: list[str], session: Session+ ) -> None:+ del tenant_id, account_id, session+ remote_roles[member_account_id] = [+ roles_by_id.get(role_id, RBACRole(id=role_id, name=role_id, type="")) for role_id in role_ids+ ]++ def fail_commit(session: Session) -> None:+ session.flush()+ raise RuntimeError("Membership commit failed")++ monkeypatch.setattr(RBACService.MemberRoles, "get", get_roles)+ monkeypatch.setattr(+ gateway,+ "owner_id",+ lambda _workspace_id, _actor_id: next(+ member_id for member_id, roles in remote_roles.items() if owner_role in roles+ ),+ )+ replace.side_effect = replace_roles+ service = WorkspaceMemberService(+ workspaces=account_domain.workspaces, accounts=account_domain.repository, access=gateway+ )++ event.listen(sqlite_session_factory, "before_commit", fail_commit)+ try:+ with pytest.raises(RuntimeError, match="Membership commit failed"):+ service.update_role(workspace_id, new_owner_id, "owner", old_owner_id)+ finally:+ event.remove(sqlite_session_factory, "before_commit", fail_commit)++ assert remote_roles[old_owner_id] == [custom_role]+ assert remote_roles[new_owner_id] == [owner_role]+ assert service.get_role(workspace_id, old_owner_id) == TenantAccountRole.OWNER+ assert service.get_role(workspace_id, new_owner_id) == TenantAccountRole.NORMAL+ replace.reset_mock()++ target_id, role = (new_owner_id, "editor") if operation == "demote_new_owner" else (third_member.id, "owner")+ with pytest.raises(NoPermissionError):+ service.update_role(workspace_id, target_id, role, old_owner_id)++ replace.assert_not_called()+ assert remote_roles[old_owner_id] == [custom_role]+ assert remote_roles[new_owner_id] == [owner_role]+ assert remote_roles[third_member.id] == []+ assert service.get_role(workspace_id, old_owner_id) == TenantAccountRole.OWNER+ assert service.get_role(workspace_id, new_owner_id) == TenantAccountRole.NORMAL+ assert service.get_role(workspace_id, third_member.id) == TenantAccountRole.NORMAL++[email protected]("new_role", ["editor", "owner"])+def test_rbac_owner_lookup_failure_prevents_role_changes(+ account_domain: AccountDomain,+ members: tuple[str, str, str],+ rbac_access: tuple[DeploymentWorkspaceMemberAccessGateway, Mock],+ monkeypatch: pytest.MonkeyPatch,+ new_role: str,+) -> None:+ workspace_id, owner_id, member_id = members+ gateway, replace = rbac_access++ def get_roles(+ tenant_id: str, account_id: str | None, member_account_id: str, *, session: Session+ ) -> MemberRolesResponse:+ del tenant_id, account_id, session+ if new_role == "editor" or member_account_id == owner_id:+ raise RuntimeError("RBAC unavailable")+ return MemberRolesResponse(account_id=member_account_id)++ monkeypatch.setattr(RBACService.MemberRoles, "get", get_roles)+ service = WorkspaceMemberService(+ workspaces=account_domain.workspaces, accounts=account_domain.repository, access=gateway+ )++ with pytest.raises(RuntimeError, match="RBAC unavailable"):+ service.update_role(workspace_id, member_id, new_role, owner_id)++ replace.assert_not_called()+ assert service.get_role(workspace_id, owner_id) == TenantAccountRole.OWNER+ assert service.get_role(workspace_id, member_id) == TenantAccountRole.NORMALdiff --git a/api/tests/unit_tests/services/workspace/test_workspace_credit_pool.py b/api/tests/unit_tests/services/workspace/test_workspace_credit_pool.pynew file mode 100644index 00000000000..73c5d44eb31--- /dev/null+++ b/api/tests/unit_tests/services/workspace/test_workspace_credit_pool.py@@ -0,0 +1,127 @@+"""Deployment billing adapter and paid-to-trial fallback regressions."""++from collections.abc import Callable+from unittest.mock import Mock++import pytest++from enums import CloudPlan, DeploymentEdition+from services.credit_pool_service import CreditPoolBalance+from services.entities.feature_entities import FeatureModel+from services.workspace import gateways+from services.workspace.gateways import DeploymentWorkspaceFeatureGateway, DeploymentWorkspacePlanGateway+++ ("plan", "paid_quota", "paid_used", "trial_quota", "expected_type", "remaining"),+ [+ (CloudPlan.TEAM, 500, 120, 100, "paid", 380),+ (CloudPlan.TEAM, -1, 999, 100, "paid", -1),+ (CloudPlan.TEAM, 500, 500, 100, "trial", 60),+ (CloudPlan.TEAM, None, 0, 100, "trial", 60),+ (CloudPlan.SANDBOX, 500, 0, 100, "trial", 60),+ (CloudPlan.SANDBOX, None, 0, None, None, None),+ ],+)+def test_effective_credit_pool(+ monkeypatch: pytest.MonkeyPatch,+ config_overrides: Callable[..., None],+ plan: CloudPlan | None,+ paid_quota: int | None,+ paid_used: int,+ trial_quota: int | None,+ expected_type: str | None,+ remaining: int | None,+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)+ monkeypatch.setattr(+ gateways.BillingService,+ "get_info",+ lambda *_a, **_k: {"subscription": {"plan": plan}, "next_credit_reset_date": 1775001600},+ )+ paid = CreditPoolBalance("tenant", "paid", paid_quota, paid_used) if paid_quota is not None else None+ trial = CreditPoolBalance("tenant", "trial", trial_quota, 40) if trial_quota is not None else None+ calls = []++ def get_pool(*, tenant_id: str, pool_type: str) -> CreditPoolBalance | None:+ calls.append((tenant_id, pool_type))+ return paid if pool_type == "paid" else trial++ monkeypatch.setattr(gateways.CreditPoolService, "get_pool", get_pool)+ result = DeploymentWorkspaceFeatureGateway().get_effective_credit_pool("tenant")+ assert result.pool_type == expected_type+ assert result.remaining_credits == remaining+ assert result.next_credit_reset_date == 1775001600+ if plan == CloudPlan.SANDBOX:+ assert calls == [("tenant", "trial")]+ elif expected_type == "paid":+ assert calls == [("tenant", "paid")]+ else:+ assert calls == [("tenant", "paid"), ("tenant", "trial")]+++ ("quota", "used", "exhausted_at", "expected"),+ [(100, 100, 123, 123), (100, 10, 123, None), (-1, 100, 123, None), (100, 100, 0, None)],+)+def test_feature_info_uses_same_pool_rules(+ monkeypatch: pytest.MonkeyPatch,+ config_overrides: Callable[..., None],+ quota: int,+ used: int,+ exhausted_at: int | None,+ expected: int | None,+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)+ features = FeatureModel(can_replace_logo=True)+ monkeypatch.setattr(gateways.FeatureService, "get_features", lambda *_a, **_k: features)+ monkeypatch.setattr(+ gateways.CreditPoolService,+ "get_pool",+ lambda **_k: CreditPoolBalance("tenant", "trial", quota, used, exhausted_at),+ )+ result = DeploymentWorkspaceFeatureGateway().get_features("tenant")+ assert result.can_replace_logo+ assert result.credits.exhausted_at == expected++[email protected]("edition", [DeploymentEdition.COMMUNITY, DeploymentEdition.ENTERPRISE])+def test_non_cloud_summary_skips_external_io(+ monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None], edition: DeploymentEdition+) -> None:+ config_overrides(DEPLOYMENT_EDITION=edition)+ billing = Mock(side_effect=AssertionError("billing must not be queried"))+ monkeypatch.setattr(gateways.BillingService, "get_info", billing)+ result = DeploymentWorkspaceFeatureGateway().get_effective_credit_pool("tenant")+ assert result.plan is None+ assert result.remaining_credits is None+ billing.assert_not_called()+++ ("edition", "bulk", "expected", "fallback_ids"),+ [+ (DeploymentEdition.CLOUD, {"w1": {"plan": "team"}}, {"w1": "team", "w2": "professional"}, ["w2"]),+ (DeploymentEdition.CLOUD, {}, {"w1": "professional", "w2": "professional"}, ["w1", "w2"]),+ (DeploymentEdition.COMMUNITY, {}, {"w1": "professional", "w2": "professional"}, ["w1", "w2"]),+ (DeploymentEdition.ENTERPRISE, {}, {"w1": "sandbox", "w2": "sandbox"}, []),+ ],+)+def test_plan_gateway_bulk_and_fallback(+ monkeypatch: pytest.MonkeyPatch,+ config_overrides: Callable[..., None],+ edition: DeploymentEdition,+ bulk: dict[str, dict[str, str]],+ expected: int | None,+ fallback_ids: list[str],+) -> None:+ config_overrides(DEPLOYMENT_EDITION=edition)+ bulk_query = Mock(return_value=bulk)+ features = FeatureModel()+ features.billing.subscription.plan = CloudPlan.PROFESSIONAL+ feature_query = Mock(return_value=features)+ monkeypatch.setattr(gateways.BillingService, "get_plan_bulk", bulk_query)+ monkeypatch.setattr(gateways.FeatureService, "get_features", feature_query)+ assert DeploymentWorkspacePlanGateway().resolve_many(["w1", "w2"]) == expected+ assert [call.args[0] for call in feature_query.call_args_list] == fallback_ids+ assert bulk_query.call_count == int(edition == DeploymentEdition.CLOUD)diff --git a/api/tests/unit_tests/services/workspace/test_workspace_file_gateway.py b/api/tests/unit_tests/services/workspace/test_workspace_file_gateway.pynew file mode 100644index 00000000000..e71253dd9c5--- /dev/null+++ b/api/tests/unit_tests/services/workspace/test_workspace_file_gateway.py@@ -0,0 +1,23 @@+"""File adapter keeps admitted identity explicit across the FileService boundary."""++from unittest.mock import Mock++from machinery.context import RequestContext+from models.account import Account+from services.file_service import FileService+from services.workspace.gateways import WorkspaceFileGateway+++def test_upload_uses_admitted_account_and_explicit_workspace() -> None:+ files = Mock(spec=FileService)+ files.upload_file.return_value = Mock(id="file-id")+ gateway = WorkspaceFileGateway(files=files)+ context = RequestContext("request", None, "account", "workspace")++ assert gateway.upload(context, filename="logo.png", content=b"image", mimetype="image/png") == "file-id"++ kwargs = files.upload_file.call_args.kwargs+ assert isinstance(kwargs["user"], Account)+ assert kwargs["user"].id == "account"+ assert kwargs["tenant_id"] == "workspace"+ assert kwargs["content"] == b"image"diff --git a/api/tests/unit_tests/services/test_workspace_member_query_service.py b/api/tests/unit_tests/services/workspace/test_workspace_member_query_service.pysimilarity index 69%rename from api/tests/unit_tests/services/test_workspace_member_query_service.pyrename to api/tests/unit_tests/services/workspace/test_workspace_member_query_service.pyindex 1525e62a7fc..5f4ca7da8f0 100644--- a/api/tests/unit_tests/services/test_workspace_member_query_service.py+++ b/api/tests/unit_tests/services/workspace/test_workspace_member_query_service.py@@ -3,14 +3,15 @@ from datetime import datetimeimport pytest+from enums.account import TenantAccountRolefrom machinery.context import RequestContext-from services.workspace_member_query_service import (- WorkspaceMemberQueryService,+from services.workspace.contracts import (WorkspaceMemberRecord,WorkspaceMemberRole,WorkspaceMemberRoleSubject,WorkspaceMemberSummary,)+from services.workspace.member_service import WorkspaceMemberQueryServicedef make_context() -> RequestContext:@@ -46,9 +47,13 @@ class RecordingMemberQuery:def __init__(self, records: Sequence[WorkspaceMemberRecord]) -> None:self.records = tuple(records)self.workspace_ids: list[str] = []+ self.requested_roles: list[TenantAccountRole | None] = []- def list_for_workspace(self, workspace_id: str) -> Sequence[WorkspaceMemberRecord]:+ def list_for_workspace(+ self, workspace_id: str, *, role: TenantAccountRole | None = None+ ) -> Sequence[WorkspaceMemberRecord]:self.workspace_ids.append(workspace_id)+ self.requested_roles.append(role)return self.records@@ -136,3 +141,33 @@ def test_list_current_propagates_role_resolution_failure() -> None:with pytest.raises(RoleResolutionError):service.list_current(make_context())++[email protected]("operators_only", [True, False])+def test_member_listing_passes_role_filter_to_repository(operators_only: bool) -> None:+ records = [make_member("operator", legacy_role="dataset_operator")]+ members = RecordingMemberQuery(records)+ roles = RecordingRoleResolver({})+ service = WorkspaceMemberQueryService(members=members, roles=roles)++ assert service.list_members("workspace-1", dataset_operators_only=operators_only) == tuple(records)+ assert members.workspace_ids == ["workspace-1"]+ assert members.requested_roles == [TenantAccountRole.DATASET_OPERATOR if operators_only else None]+ assert roles.calls == []+++ ("count", "page", "limit", "expected_ids"),+ [(5, 2, 2, ["2", "3"]), (5, 3, 2, ["4"]), (5, 4, 2, []), (0, 1, 20, [])],+)+def test_member_page_preserves_total_and_order(count: int, page: int, limit: int, expected_ids: list[str]) -> None:+ members = RecordingMemberQuery([make_member(str(index)) for index in range(count)])+ roles = RecordingRoleResolver({})+ service = WorkspaceMemberQueryService(members=members, roles=roles)++ result = service.list_page(make_context(), page=page, limit=limit)++ assert result.total == count+ assert [member.id for member in result.members] == expected_ids+ assert members.workspace_ids == ["workspace-1"]+ assert roles.calls == []diff --git a/api/tests/unit_tests/services/test_workspace_member_role_resolver.py b/api/tests/unit_tests/services/workspace/test_workspace_member_role_resolver.pysimilarity index 82%rename from api/tests/unit_tests/services/test_workspace_member_role_resolver.pyrename to api/tests/unit_tests/services/workspace/test_workspace_member_role_resolver.pyindex b40f77da45c..d955a251694 100644--- a/api/tests/unit_tests/services/test_workspace_member_role_resolver.py+++ b/api/tests/unit_tests/services/workspace/test_workspace_member_role_resolver.py@@ -3,9 +3,9 @@ from unittest.mock import MagicMockimport pytest-from services import workspace_member_role_resolverfrom services.enterprise.rbac_service import MemberRolesResponse, RBACRole-from services.workspace_member_query_service import WorkspaceMemberRole, WorkspaceMemberRoleSubject+from services.workspace import gateways+from services.workspace.contracts import WorkspaceMemberRole, WorkspaceMemberRoleSubjectdef make_subject(account_id: str, *, legacy_role: str = "normal") -> WorkspaceMemberRoleSubject:@@ -16,7 +16,7 @@ def make_subject(account_id: str, *, legacy_role: str = "normal") -> WorkspaceMedef batch_get(monkeypatch: pytest.MonkeyPatch) -> MagicMock:batch_get = MagicMock()monkeypatch.setattr(- workspace_member_role_resolver.enterprise_rbac_service.RBACService.MemberRoles,+ gateways.enterprise_rbac_service.RBACService.MemberRoles,"batch_get",batch_get,)@@ -25,7 +25,7 @@ def batch_get(monkeypatch: pytest.MonkeyPatch) -> MagicMock:def configure_rbac(monkeypatch: pytest.MonkeyPatch, *, enabled: bool) -> None:monkeypatch.setattr(- workspace_member_role_resolver,+ gateways,"dify_config",SimpleNamespace(RBAC_ENABLED=enabled),)@@ -39,7 +39,7 @@ def test_legacy_mode_projects_join_roles_without_enterprise_call(owner = make_subject("owner", legacy_role="owner")member = make_subject("member")- result = workspace_member_role_resolver.DeploymentWorkspaceMemberRoleResolver().resolve_many(+ result = gateways.DeploymentWorkspaceMemberRoleResolver().resolve_many("workspace-1","actor-1",[owner, member],@@ -77,7 +77,7 @@ def test_rbac_mode_maps_batch_response_without_legacy_fallback()]- result = workspace_member_role_resolver.DeploymentWorkspaceMemberRoleResolver().resolve_many(+ result = gateways.DeploymentWorkspaceMemberRoleResolver().resolve_many("workspace-1","actor-1",[owner, omitted],@@ -101,7 +101,7 @@ def test_rbac_failure_propagates(batch_get.side_effect = RoleResolutionError("enterprise unavailable")with pytest.raises(RoleResolutionError, match="enterprise unavailable"):- workspace_member_role_resolver.DeploymentWorkspaceMemberRoleResolver().resolve_many(+ gateways.DeploymentWorkspaceMemberRoleResolver().resolve_many("workspace-1","actor-1",[make_subject("member-1")],@@ -114,7 +114,7 @@ def test_empty_member_list_skips_enterprise_call() -> None:configure_rbac(monkeypatch, enabled=True)- result = workspace_member_role_resolver.DeploymentWorkspaceMemberRoleResolver().resolve_many(+ result = gateways.DeploymentWorkspaceMemberRoleResolver().resolve_many("workspace-1","actor-1",[],diff --git a/api/tests/unit_tests/services/workspace/test_workspace_provisioning.py b/api/tests/unit_tests/services/workspace/test_workspace_provisioning.pynew file mode 100644index 00000000000..472c4fd7948--- /dev/null+++ b/api/tests/unit_tests/services/workspace/test_workspace_provisioning.py@@ -0,0 +1,404 @@+"""Internal provisioning policy and the existing tenant write path."""++from collections.abc import Callable+from datetime import datetime+from typing import cast+from unittest.mock import Mock++import pytest+from blinker import Signal+from sqlalchemy import Select, event, select+from sqlalchemy.dialects import postgresql+from sqlalchemy.engine import Connection+from sqlalchemy.orm import Mapper, ORMExecuteState, Session, sessionmaker++from enums import DeploymentEdition+from models import TenantCreditPool+from models.account import Account, Tenant, TenantAccountJoin, TenantAccountRole, TenantPluginAutoUpgradeStrategy+from repositories.account.repository import SQLAlchemyAccountRepository+from repositories.workspace.workspace_repository import WorkspaceRepository+from services.account_errors import AccountNotFoundError+from services.entities.account_entities import AccountSnapshot+from services.entities.feature_entities import LicenseModel+from services.errors.workspace import (+ InvalidWorkspaceMemberRoleError,+ WorkspaceNotFoundError,+ WorkspaceOwnerNotFoundError,+)+from services.workspace import gateways+from services.workspace.contracts import CreatedWorkspace, WorkspaceCreation+from services.workspace.gateways import WorkspaceProvisioningEffectsGateway+from services.workspace.provisioning_service import (+ WorkspaceCreationPolicy,+ WorkspaceMembershipQuery,+ WorkspaceMemberWriter,+ WorkspaceOwnerQuery,+ WorkspaceProvisioningEffects,+ WorkspaceProvisioningService,+ WorkspaceProvisioningStore,+)+from tests.unit_tests.account_domain import AccountDomain++OWNER = AccountSnapshot(+ "account",+ "Owner",+ "[email protected]",+ None,+ False,+ "en-US",+ "light",+ "UTC",+ None,+ None,+ "active",+ datetime(2026, 1, 1),+ datetime(2026, 1, 1),+)+++def test_owner_lookup_is_exact_and_tolerates_duplicate_emails(sqlite_session_factory: sessionmaker[Session]) -> None:+ with sqlite_session_factory() as session:+ first = Account(name="First", email="[email protected]")+ second = Account(name="Second", email="[email protected]")+ session.add_all([first, second])+ session.commit()+ owner_ids = {first.id, second.id}+ repository = SQLAlchemyAccountRepository(sqlite_session_factory)+ gateway = Mock(spec=WorkspaceProvisioningStore)+ service = _service(owners=repository, provisioning=gateway)+ service.create(name="Test", owner_email="[email protected]")+ assert gateway.provision.call_args.kwargs["owner_id"] in owner_ids+ with pytest.raises(WorkspaceOwnerNotFoundError):+ service.create(name="Test", owner_email="[email protected]")+ assert gateway.provision.call_count == 1++[email protected]("role", ["owner", "unknown", "ADMIN"])+def test_invalid_roles_are_rejected_before_writes(role: str) -> None:+ gateway = Mock(spec=WorkspaceProvisioningStore)+ service = _service(owners=Mock(spec=WorkspaceOwnerQuery), provisioning=gateway)+ with pytest.raises(InvalidWorkspaceMemberRoleError):+ service.join_member(+ workspace_id="w", account_id="a", email="[email protected]", role=role, operator_account_id=None+ )+ cast(Mock, service._members).join_member.assert_not_called()+++def test_member_operator_is_forwarded() -> None:+ gateway = Mock(spec=WorkspaceProvisioningStore)+ service = _service(owners=Mock(spec=WorkspaceOwnerQuery), provisioning=gateway)+ service.join_member(+ workspace_id="w", account_id="a", email="[email protected]", role="editor", operator_account_id="operator"+ )+ cast(Mock, service._members).join_member.assert_called_once_with(+ workspace_id="w",+ account_id="a",+ email="[email protected]",+ role=TenantAccountRole.EDITOR,+ operator_account_id="operator",+ )+++def test_missing_owner_is_rejected_before_creation() -> None:+ owners = Mock(spec=WorkspaceOwnerQuery)+ owners.find_first_by_email.return_value = None+ gateway = Mock(spec=WorkspaceProvisioningStore)+ service = _service(owners=owners, provisioning=gateway)+ with pytest.raises(WorkspaceOwnerNotFoundError):+ service.create(name="Test", owner_email="[email protected]")+ gateway.provision.assert_not_called()++[email protected]("owner_email", [None, "[email protected]"])+def test_create_delegation(owner_email: str | None) -> None:+ owners = Mock(spec=WorkspaceOwnerQuery)+ owners.find_first_by_email.return_value = OWNER+ gateway = Mock(spec=WorkspaceProvisioningStore)+ result = CreatedWorkspace("w", "Test", "sandbox", "normal", None, None, None, {})+ gateway.provision.return_value = result+ service = _service(owners=owners, provisioning=gateway)+ assert service.create(name="Test", owner_email=owner_email) is result+ assert gateway.provision.call_args.kwargs["owner_id"] == (OWNER.id if owner_email else None)+ if owner_email is None:+ owners.find_first_by_email.assert_not_called()+++def gateway(+ sqlite_session_factory: sessionmaker[Session],+ monkeypatch: pytest.MonkeyPatch,+ config_overrides: Callable[..., None],+) -> tuple[WorkspaceProvisioningService, Signal]:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY, RBAC_ENABLED=False)+ monkeypatch.setattr(gateways.SystemFeatureService, "is_workspace_creation_allowed", lambda: True)+ monkeypatch.setattr(gateways.SystemFeatureService, "get_license", lambda: LicenseModel())+ monkeypatch.setattr(gateways, "generate_key_pair", lambda _workspace_id: "public-key")+ signal = Signal()+ monkeypatch.setattr(gateways, "tenant_was_created", signal)+ return _service(+ owners=SQLAlchemyAccountRepository(sqlite_session_factory),+ provisioning=WorkspaceRepository(sqlite_session_factory),+ effects=WorkspaceProvisioningEffectsGateway(session_factory=sqlite_session_factory),+ ), signal++[email protected]("with_owner", [False, True])+def test_creation_reuses_defaults_and_emits_one_event(+ gateway: tuple[WorkspaceProvisioningService, Signal],+ sqlite_session_factory: sessionmaker[Session],+ with_owner: bool,+ config_overrides: Callable[..., None],+) -> None:+ adapter, signal = gateway+ config_overrides(HOSTED_POOL_CREDITS=123)+ with sqlite_session_factory() as session:+ account = Account(name="Owner", email="[email protected]")+ session.add(account)+ session.commit()+ account_id = account.id+ emitted = []++ def record(tenant: CreatedWorkspace) -> None:+ with sqlite_session_factory() as session:+ assert session.get(Tenant, tenant.id) is not None+ emitted.append(tenant.id)++ signal.connect(record)+ result = adapter.create(name="Created", owner_email="[email protected]" if with_owner else None)+ assert result.name == "Created"+ assert result.encrypt_public_key == "public-key"+ assert emitted == [result.id]+ with sqlite_session_factory() as session:+ tenant = session.get(Tenant, result.id)+ assert tenant is not None+ assert tenant.name == "Created"+ pool = session.scalar(select(TenantCreditPool).where(TenantCreditPool.tenant_id == result.id))+ assert pool is not None+ assert pool.quota_limit == 123+ assert pool.quota_used == 0+ assert pool.pool_type == "trial"+ strategies = session.scalars(+ select(TenantPluginAutoUpgradeStrategy).where(TenantPluginAutoUpgradeStrategy.tenant_id == result.id)+ ).all()+ assert len(strategies) == len(gateways.TenantPluginAutoUpgradeCategory)+ for strategy in strategies:+ assert strategy.strategy_setting == gateways.PluginAutoUpgradeService.default_strategy_setting_for_category(+ strategy.category+ )+ assert strategy.upgrade_time_of_day == gateways.PluginAutoUpgradeService.default_upgrade_time_of_day(+ result.id+ )+ membership = session.scalar(select(TenantAccountJoin).where(TenantAccountJoin.tenant_id == result.id))+ if with_owner:+ assert membership is not None+ assert membership.account_id == account_id+ assert membership.role == TenantAccountRole.OWNER+ else:+ assert membership is None+++def test_missing_owner_cannot_create_or_emit(+ gateway: tuple[WorkspaceProvisioningService, Signal], sqlite_session_factory: sessionmaker[Session]+) -> None:+ adapter, signal = gateway+ emitted = []++ def record(tenant: CreatedWorkspace) -> None:+ emitted.append(tenant.id)++ signal.connect(record)+ with pytest.raises(WorkspaceOwnerNotFoundError):+ adapter.create(name="Absent", owner_email="[email protected]")+ with sqlite_session_factory() as session:+ assert session.scalar(select(Tenant.id)) is None+ assert emitted == []+++def test_membership_uses_explicit_session_and_preserves_current(+ account_domain: AccountDomain,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ adapter = account_domain.members+ with sqlite_session_factory() as session:+ account = Account(name="Member", email="[email protected]")+ tenant = Tenant(name="Target")+ session.add_all([account, tenant])+ session.commit()+ account_id, workspace_id = (account.id, tenant.id)+ for role in (TenantAccountRole.NORMAL, TenantAccountRole.EDITOR):+ result = adapter.join_member(+ workspace_id=workspace_id,+ account_id=account_id,+ email="[email protected]",+ role=role,+ operator_account_id=None,+ )+ assert result.role == role.value+ with sqlite_session_factory() as session:+ membership = session.scalar(select(TenantAccountJoin))+ assert membership is not None+ assert membership.role == TenantAccountRole.EDITOR+ assert not membership.current+ with pytest.raises(AccountNotFoundError):+ adapter.join_member(+ workspace_id=workspace_id,+ account_id=account_id,+ email="[email protected]",+ role=TenantAccountRole.NORMAL,+ operator_account_id=None,+ )+ with pytest.raises(WorkspaceNotFoundError):+ adapter.join_member(+ workspace_id="absent",+ account_id=account_id,+ email="[email protected]",+ role=TenantAccountRole.NORMAL,+ operator_account_id=None,+ )+++def test_provisioning_rolls_back_the_entire_aggregate_when_defaults_fail(+ account_domain: AccountDomain, sqlite_session_factory: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch+) -> None:+ emitted: list[str] = []+ signal = Signal()+ monkeypatch.setattr(gateways, "tenant_was_created", signal)++ def record(tenant: CreatedWorkspace) -> None:+ emitted.append(tenant.id)++ def reject_pool(_mapper: Mapper[TenantCreditPool], _connection: Connection, _pool: TenantCreditPool) -> None:+ raise RuntimeError("Pool write failed")++ signal.connect(record)+ event.listen(TenantCreditPool, "before_insert", reject_pool)+ try:+ with pytest.raises(RuntimeError, match="Pool write failed"):+ account_domain.provisioning.create_with_owner_workspace(+ email="[email protected]", name="New", interface_language="en-US", timezone="UTC", ip_address="127.0.0.1"+ )+ finally:+ event.remove(TenantCreditPool, "before_insert", reject_pool)++ with sqlite_session_factory() as session:+ for model in (Account, Tenant, TenantAccountJoin, TenantPluginAutoUpgradeStrategy, TenantCreditPool):+ assert session.scalar(select(model.id)) is None+ assert emitted == []+++def test_initial_workspace_creation_is_idempotent(+ account_domain: AccountDomain, sqlite_session_factory: sessionmaker[Session]+) -> None:+ account = account_domain.accounts.create_account("[email protected]", "Owner", "en-US")+ account_domain.provisioning.ensure_owner_workspace(account.id)+ account_domain.provisioning.ensure_owner_workspace(account.id)++ with sqlite_session_factory() as session:+ assert len(session.scalars(select(Tenant.id)).all()) == 1+ assert len(session.scalars(select(TenantCreditPool.id)).all()) == 1+++def test_competing_initial_workspace_skips_key_and_owner_binding(+ account_domain: AccountDomain, sqlite_session_factory: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch+) -> None:+ account = account_domain.accounts.create_account("[email protected]", "Owner", "en-US")+ effects = Mock(spec=WorkspaceProvisioningEffects)+ effects.prepare.side_effect = [+ WorkspaceCreation("winner", "Owner's Workspace", "winner-key", 123, 0, {}),+ WorkspaceCreation("skipped", "Owner's Workspace", "orphan-key", 123, 0, {}),+ ]+ monkeypatch.setattr(account_domain.provisioning, "_effects", effects)+ competing_repository = WorkspaceRepository(sqlite_session_factory)+ competing_service = WorkspaceProvisioningService(+ owners=account_domain.repository,+ provisioning=competing_repository,+ effects=effects,+ policies=account_domain.policy,+ memberships=competing_repository,+ members=account_domain.members,+ )+ has_active_workspace = account_domain.workspaces.has_active_for_account++ def finish_competing_request_after_precheck(account_id: str) -> bool:+ # Both requests see no workspace. The winner commits before the losing+ # request reaches its locked recheck in the real repository.+ observed = has_active_workspace(account_id)+ assert not observed+ competing_service.ensure_owner_workspace(account_id)+ return observed++ monkeypatch.setattr(account_domain.workspaces, "has_active_for_account", finish_competing_request_after_precheck)+ account_domain.provisioning.ensure_owner_workspace(account.id)++ effects.prepare.assert_called_once_with("Owner's Workspace")+ effects.bind_owner.assert_called_once_with("winner", account.id)+ effects.created.assert_called_once()+ with sqlite_session_factory() as session:+ assert list(session.scalars(select(Tenant.id))) == ["winner"]+ assert list(session.scalars(select(TenantAccountJoin.tenant_id))) == ["winner"]+ assert list(session.scalars(select(TenantCreditPool.tenant_id))) == ["winner"]+++def test_initial_workspace_locks_before_preparation_and_publishes_after_commit(+ account_domain: AccountDomain, sqlite_session_factory: sessionmaker[Session], monkeypatch: pytest.MonkeyPatch+) -> None:+ account = account_domain.accounts.create_account("[email protected]", "Owner", "en-US")+ phases: list[str] = []+ effects = Mock(spec=WorkspaceProvisioningEffects)++ def record_lock(execution: ORMExecuteState) -> None:+ # SQLite exercises persistence; compile the actual ORM statement for+ # PostgreSQL to verify the row-lock clause that SQLite cannot execute.+ statement = execution.statement+ if isinstance(statement, Select) and "FOR UPDATE" in str(statement.compile(dialect=postgresql.dialect())):+ phases.append("lock")++ def prepare(_name: str) -> WorkspaceCreation:+ phases.append("prepare")+ return WorkspaceCreation("workspace", "Owner's Workspace", "key", 123, 0, {})++ def bind_owner(_workspace_id: str, _account_id: str) -> None:+ phases.append("bind")++ def committed(_session: Session) -> None:+ phases.append("commit")++ def published(_workspace: CreatedWorkspace, *, owner_id: str | None) -> None:+ assert owner_id == account.id+ phases.append("publish")++ effects.prepare.side_effect = prepare+ effects.bind_owner.side_effect = bind_owner+ effects.created.side_effect = published+ monkeypatch.setattr(account_domain.provisioning, "_effects", effects)+ event.listen(sqlite_session_factory, "do_orm_execute", record_lock)+ event.listen(sqlite_session_factory, "after_commit", committed)+ try:+ account_domain.provisioning.ensure_owner_workspace(account.id)+ finally:+ event.remove(sqlite_session_factory, "do_orm_execute", record_lock)+ event.remove(sqlite_session_factory, "after_commit", committed)++ assert phases == ["lock", "prepare", "bind", "commit", "publish"]+++def _service(+ *,+ owners: WorkspaceOwnerQuery,+ provisioning: WorkspaceProvisioningStore,+ effects: WorkspaceProvisioningEffects | None = None,+) -> WorkspaceProvisioningService:+ policy = Mock(spec=WorkspaceCreationPolicy)+ policy.has_workspace_capacity.return_value = True+ if effects is None:+ prepared = Mock(spec=WorkspaceProvisioningEffects)+ prepared.prepare.return_value = WorkspaceCreation("w", "Test", "key", 123, 0, {})+ effects = prepared+ return WorkspaceProvisioningService(+ effects=effects,+ owners=owners,+ provisioning=provisioning,+ policies=policy,+ memberships=Mock(spec=WorkspaceMembershipQuery),+ members=Mock(spec=WorkspaceMemberWriter),+ )diff --git a/api/tests/unit_tests/services/workspace/test_workspace_service.py b/api/tests/unit_tests/services/workspace/test_workspace_service.pynew file mode 100644index 00000000000..652d01ccc7e--- /dev/null+++ b/api/tests/unit_tests/services/workspace/test_workspace_service.py@@ -0,0 +1,150 @@+"""Workspace orchestration without Flask or ORM dependencies."""++from dataclasses import replace+from datetime import datetime+from unittest.mock import Mock++import pytest++from enums import CloudPlan+from machinery.context import RequestContext+from services.errors.file import UnsupportedFileTypeError+from services.errors.workspace import WorkspaceArchivedError, WorkspaceNotFoundError+from services.workspace.contracts import (+ EffectiveCreditPool,+ WorkspaceCustomConfig,+ WorkspaceCustomConfigChanges,+ WorkspaceFeatures,+ WorkspaceSnapshot,+)+from services.workspace.service import (+ WorkspaceFeatureGateway,+ WorkspaceLogoGateway,+ WorkspaceService,+ WorkspaceStore,+)++CONTEXT = RequestContext("request", None, "account", "workspace")+WORKSPACE = WorkspaceSnapshot(+ "workspace", "Test", "normal", datetime(2026, 1, 1), "editor", WorkspaceCustomConfig(True, "stored-logo"), True+)+++def dependencies() -> tuple[WorkspaceService, Mock, Mock, Mock]:+ store = Mock(spec=WorkspaceStore)+ features = Mock(spec=WorkspaceFeatureGateway)+ logos = Mock(spec=WorkspaceLogoGateway)+ store.get_for_account.return_value = WORKSPACE+ features.logo_url.return_value = "https://files/workspaces/workspace/webapp-logo"+ features.get_features.return_value = WorkspaceFeatures(True, EffectiveCreditPool())+ return (WorkspaceService(workspaces=store, features=features, logos=logos), store, features, logos)+++ ("plan", "limit", "used", "remaining"),+ [+ (CloudPlan.SANDBOX, 100, 30, 70),+ (CloudPlan.TEAM, -1, 999, -1),+ (CloudPlan.TEAM, 10, 20, 0),+ (None, None, None, None),+ ],+)+def test_summary_uses_context_identity_and_credit_snapshot(+ dependencies: tuple[WorkspaceService, Mock, Mock, Mock],+ plan: CloudPlan | None,+ limit: int | None,+ used: int | None,+ remaining: int | None,+) -> None:+ service, store, features, _ = dependencies+ features.get_effective_credit_pool.return_value = EffectiveCreditPool(plan=plan, quota_limit=limit, quota_used=used)+ assert service.current_summary(CONTEXT) == {+ "id": "workspace",+ "name": "Test",+ "role": "editor",+ "plan": plan,+ "credits": remaining,+ }+ store.get_for_account.assert_called_once_with("workspace", "account")+++def test_archived_workspace_does_not_read_billing(dependencies: tuple[WorkspaceService, Mock, Mock, Mock]) -> None:+ service, store, features, _ = dependencies+ store.get_for_account.return_value = replace(WORKSPACE, status="archive")+ with pytest.raises(WorkspaceArchivedError):+ service.current_summary(CONTEXT)+ features.get_effective_credit_pool.assert_not_called()+++def test_missing_workspace(dependencies: tuple[WorkspaceService, Mock, Mock, Mock]) -> None:+ service, store, _, _ = dependencies+ store.get_for_account.return_value = None+ with pytest.raises(WorkspaceNotFoundError):+ service.custom_config(CONTEXT)+++ ("changes", "expected"),+ [+ (WorkspaceCustomConfigChanges(None, None), WorkspaceCustomConfig(True, "stored-logo")),+ (WorkspaceCustomConfigChanges(False, None), WorkspaceCustomConfig(False, "stored-logo")),+ (WorkspaceCustomConfigChanges(None, ""), WorkspaceCustomConfig(True, "")),+ (WorkspaceCustomConfigChanges(None, "new-logo"), WorkspaceCustomConfig(True, "new-logo")),+ ],+)+def test_config_patch_preserves_omitted_fields_and_honors_false_and_empty(+ dependencies: tuple[WorkspaceService, Mock, Mock, Mock],+ changes: WorkspaceCustomConfigChanges,+ expected: WorkspaceCustomConfig,+) -> None:+ service, store, _, _ = dependencies+ store.update_custom_config.return_value = replace(WORKSPACE, custom_config=expected)+ service.update_custom_config(CONTEXT, changes)+ store.update_custom_config.assert_called_once_with(workspace_id="workspace", account_id="account", changes=expected)+++ ("can_replace", "has_manager", "includes_config"), [(True, True, True), (True, False, False), (False, True, False)]+)+def test_tenant_info_preserves_workspace_brand_visibility(+ dependencies: tuple[WorkspaceService, Mock, Mock, Mock], can_replace: bool, has_manager: bool, includes_config: bool+) -> None:+ service, store, features, _ = dependencies+ store.rename.return_value = replace(WORKSPACE, has_privileged_member=has_manager)+ features.get_features.return_value = WorkspaceFeatures(can_replace, EffectiveCreditPool())+ result = service.rename(CONTEXT, "New")+ assert ("custom_config" in result) is includes_config+ assert result["plan"] is None+ assert "trial_credits" not in result+++def test_switch_serializes_effective_exhausted_pool(dependencies: tuple[WorkspaceService, Mock, Mock, Mock]) -> None:+ service, store, features, _ = dependencies+ store.switch.return_value = WORKSPACE+ features.get_features.return_value = WorkspaceFeatures(+ True, EffectiveCreditPool(CloudPlan.TEAM, "trial", 100, 100, 1770000000, 1780000000)+ )+ result = service.switch(CONTEXT, "target")+ assert result["trial_credits"] == 100+ assert result["trial_credits_used"] == 100+ assert result["trial_credits_exhausted_at"] == 1770000000+ assert result["next_credit_reset_date"] == 1780000000+ store.switch.assert_called_once_with(account_id="account", workspace_id="target")++[email protected]("filename", ["logo.jpg", "file.txt", "logo"])+def test_invalid_logo_never_reaches_storage(+ dependencies: tuple[WorkspaceService, Mock, Mock, Mock], filename: str+) -> None:+ service, _, _, logos = dependencies+ with pytest.raises(UnsupportedFileTypeError):+ service.upload_logo(CONTEXT, filename=filename, content=b"data", mimetype="image/jpeg")+ logos.upload.assert_not_called()+++def test_logo_delegation(dependencies: tuple[WorkspaceService, Mock, Mock, Mock]) -> None:+ service, _, _, logos = dependencies+ logos.upload.return_value = "file-id"+ assert service.upload_logo(CONTEXT, filename="logo.SVG", content=b"<svg/>", mimetype="image/svg+xml") == "file-id"+ logos.upload.assert_called_once_with(CONTEXT, filename="logo.SVG", content=b"<svg/>", mimetype="image/svg+xml")diff --git a/api/tests/unit_tests/tasks/test_initialize_created_app_rbac_access_task.py b/api/tests/unit_tests/tasks/test_initialize_created_app_rbac_access_task.pyindex b9d96fc01db..deae098c009 100644--- a/api/tests/unit_tests/tasks/test_initialize_created_app_rbac_access_task.py+++ b/api/tests/unit_tests/tasks/test_initialize_created_app_rbac_access_task.py@@ -1,7 +1,9 @@from unittest.mock import MagicMockimport pytest+from flask import Flask+from extensions.ext_application_services import ApplicationServices, application_servicesfrom tasks.initialize_created_app_rbac_access_task import initialize_created_app_rbac_access_taskfrom tests.unit_tests.config_override import apply_config_overrides@@ -24,9 +26,9 @@ def test_initialize_created_app_rbac_access_task_batches_workspace_members(monkeapply_config_overrides(monkeypatch, RBAC_ENABLED=True)monkeypatch.setattr(- task_module.TenantService,+ application_services().workspaces.management,"iter_member_account_id_batches",- lambda tenant_id, batch_size, session: iter([["acct-1", "acct-2"], ["acct-3"]]),+ lambda tenant_id, batch_size: iter([("acct-1", "acct-2"), ("acct-3",)]),)replace_whitelist = MagicMock()replace_user_access_policies = MagicMock()@@ -66,9 +68,9 @@ def test_initialize_created_app_rbac_access_task_targets_the_resource_that_was_papply_config_overrides(monkeypatch, RBAC_ENABLED=True)monkeypatch.setattr(- task_module.TenantService,+ application_services().workspaces.management,"iter_member_account_id_batches",- lambda tenant_id, batch_size, session: iter([["acct-1"]]),+ lambda tenant_id, batch_size: iter([("acct-1",)]),)rbac_service = task_module.enterprise_rbac_service.RBACServiceaccess_clients = {@@ -100,9 +102,9 @@ def test_initialize_created_app_rbac_access_task_retries_on_failure(monkeypatch:apply_config_overrides(monkeypatch, RBAC_ENABLED=True)monkeypatch.setattr(- task_module.TenantService,+ application_services().workspaces.management,"iter_member_account_id_batches",- lambda tenant_id, batch_size, session: iter([["acct-1"]]),+ lambda tenant_id, batch_size: iter([("acct-1",)]),)monkeypatch.setattr(task_module.enterprise_rbac_service.RBACService.AppAccess,@@ -206,3 +208,10 @@ def test_sync_joined_workspace_member_rbac_access_task_appends_auto_included_resassert [item.agent_id for item in agent_call["data"]] == ["agent-1"]assert agent_call["data"][0].account_ids == ["member-1"]assert agent_call["data"][0].policy_id == task_module.APP_RBAC_DEFAULT_ACCESS_POLICY_ID++[email protected](autouse=True)+def _account_services(+ monkeypatch: pytest.MonkeyPatch, app: Flask, account_application_services: ApplicationServices+) -> None:+ monkeypatch.setitem(app.extensions, "application_services", account_application_services)diff --git a/api/tests/unit_tests/test_integration_account_fixtures.py b/api/tests/unit_tests/test_integration_account_fixtures.pynew file mode 100644index 00000000000..6e09594b00e--- /dev/null+++ b/api/tests/unit_tests/test_integration_account_fixtures.py@@ -0,0 +1,37 @@+"""Exercise integration-test identity setup with real SQLite persistence."""++import pytest+from sqlalchemy import select+from sqlalchemy.orm import Session++from extensions.ext_application_services import ApplicationServices+from models.account import Account, TenantAccountJoin, TenantAccountRole+from tests.test_containers_integration_tests.helpers import accounts as account_fixtures+from tests.unit_tests.account_domain import AccountDomain+++def test_owner_workspace_fixture_seeds_once_when_self_service_creation_is_disabled(+ account_application_services: ApplicationServices,+ account_domain: AccountDomain,+ sqlite_session: Session,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ account_domain.policy.is_workspace_creation_allowed.return_value = False+ monkeypatch.setattr(account_fixtures, "application_services", lambda: account_application_services)+ account = account_fixtures.create_account(+ email="[email protected]", name="Owner", interface_language="en-US", session=sqlite_session+ )++ account_fixtures.create_owner_workspace(account, name="Fixture workspace", session=sqlite_session)+ account_fixtures.create_owner_workspace(account, name="Ignored", session=sqlite_session)++ tenant = account.current_tenant+ assert tenant is not None+ assert tenant.name == "Fixture workspace"+ assert sqlite_session.get(Account, account.id) is account+ memberships = sqlite_session.scalars(+ select(TenantAccountJoin).where(TenantAccountJoin.account_id == account.id)+ ).all()+ assert [(membership.tenant_id, membership.role) for membership in memberships] == [+ (tenant.id, TenantAccountRole.OWNER)+ ]diff --git a/packages/contracts/generated/api/console/workspaces/orpc.gen.ts b/packages/contracts/generated/api/console/workspaces/orpc.gen.tsindex c2615dc448b..76beec5a5fd 100644--- a/packages/contracts/generated/api/console/workspaces/orpc.gen.ts+++ b/packages/contracts/generated/api/console/workspaces/orpc.gen.ts@@ -1725,20 +1725,12 @@ export const models2 = {modelTypes,}-/**- * Get workspace permission settings- *- * Returns permission flags that control workspace features like member invitations and owner transfer.- */export const get22 = oc.route({- description:- 'Returns permission flags that control workspace features like member invitations and owner transfer.',inputStructure: 'detailed',method: 'GET',operationId: 'getWorkspacesCurrentPermission',path: '/workspaces/current/permission',- summary: 'Get workspace permission settings',tags: ['console'],}).output(zGetWorkspacesCurrentPermissionResponse)