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): decouple system features and web adapters (#40772)
Byron.wangc4ea4065861f
diff --git a/api/.importlinter b/api/.importlinterindex 7cf69c0c515..2df3d8d8d68 100644--- a/api/.importlinter+++ b/api/.importlinter@@ -65,7 +65,7 @@ ignore_imports =core.app.workflow.layers.persistence -> services.workflow.inspector_eventscore.datasource.datasource_manager -> services.datasource_provider_servicecore.helper.credential_utils -> services.enterprise.plugin_manager_service- core.helper.credential_utils -> services.feature_service+ core.helper.credential_utils -> services.system_feature_servicecore.indexing_runner -> services.vector_space_admission_servicecore.mcp.auth_client -> servicescore.provider_manager -> services.credential_permission_service@@ -99,9 +99,9 @@ ignore_imports =core.workflow.nodes.agent_v2.workspace_retirement_layer -> tasks.collect_agent_resources_tasklibs.device_flow_security -> controllers.openapi._modelslibs.device_flow_security -> services.entities.feature_entities- libs.device_flow_security -> services.feature_service+ libs.device_flow_security -> services.system_feature_servicelibs.email_i18n -> services.entities.feature_entities- libs.email_i18n -> services.feature_service+ libs.email_i18n -> services.system_feature_servicelibs.external_api -> corelibs.external_api -> core.errors.errorlibs.external_api -> extensions.ext_logging@@ -117,7 +117,6 @@ ignore_imports =libs.oauth_bearer -> modelslibs.rsa -> extensions.ext_storagelibs.workspace_permission -> services.enterprise.enterprise_service- libs.workspace_permission -> services.feature_serviceservices.account_service -> controllersservices.account_service -> controllers.console.errorservices.app_generate_service -> controllers.console.app.workflow@@ -387,6 +386,37 @@ forbidden_modules =sqlalchemywerkzeug+[importlinter:contract:inner-mail-service-boundary]+name = Inner mail application service is framework and implementation neutral+type = forbidden+source_modules =+ services.inner_mail_service+forbidden_modules =+ configs+ controllers+ extensions+ flask+ models+ repositories+ sqlalchemy+ tasks+ werkzeug++[importlinter:contract:web-passport-service-boundary]+name = Web passport application service is framework and persistence neutral+type = forbidden+source_modules =+ services.web_passport_service+forbidden_modules =+ configs+ controllers+ extensions+ flask+ models+ repositories+ sqlalchemy+ werkzeug+[importlinter:contract:account-activation-service-boundary]name = Account activation application service is framework and persistence neutraltype = forbiddendiff --git a/api/controllers/console/agent/roster.py b/api/controllers/console/agent/roster.pyindex f95f9d8b00f..739a4ac5399 100644--- a/api/controllers/console/agent/roster.py+++ b/api/controllers/console/agent/roster.py@@ -80,7 +80,7 @@ from services.agent.roster_service import AgentRosterServicefrom services.app_service import AgentAppPublicationCounts, AppListParams, AppService, CreateAppParamsfrom services.enterprise.enterprise_service import EnterpriseServicefrom services.entities.agent_entities import ComposerSavePayload, RosterListQuery-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServiceAgentPublicationStatus = Literal["published", "drafts"]@@ -387,7 +387,7 @@ def _serialize_agent_app_detail("""app_model = AppService().get_app(app_model, session=session)- if FeatureService.get_system_features().webapp_auth.enabled:+ if SystemFeatureService.is_webapp_auth_enabled():app_setting = EnterpriseService.WebAppAuth.get_app_access_mode_by_id(app_id=str(app_model.id))app_model.access_mode = app_setting.access_mode # type: ignore[attr-defined]diff --git a/api/controllers/console/app/app.py b/api/controllers/console/app/app.pyindex 358fd60c0fe..37abb584198 100644--- a/api/controllers/console/app/app.py+++ b/api/controllers/console/app/app.py@@ -77,7 +77,7 @@ from services.entities.knowledge_entities.knowledge_entities import (WeightVectorSetting,)from services.errors.account import NoPermissionError-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServicefrom tasks.initialize_created_app_rbac_access_task import initialize_created_app_rbac_access_taskALLOW_CREATE_APP_MODES = ["chat", "agent-chat", "advanced-chat", "workflow", "completion"]@@ -516,7 +516,7 @@ class AppImportResponse(ResponseModel):def _enrich_app_list_items(session: Session, *, apps: Sequence[App], tenant_id: str) -> None:- if FeatureService.get_system_features().webapp_auth.enabled:+ if SystemFeatureService.is_webapp_auth_enabled():app_ids = [str(app.id) for app in apps]res = EnterpriseService.WebAppAuth.batch_get_app_access_mode_by_id(app_ids=app_ids)if len(res) != len(app_ids):@@ -877,7 +877,7 @@ class AppApi(Resource):app_model = app_service.get_app(app_model, session=session)- if FeatureService.get_system_features().webapp_auth.enabled:+ if SystemFeatureService.is_webapp_auth_enabled():app_setting = EnterpriseService.WebAppAuth.get_app_access_mode_by_id(app_id=str(app_model.id))app_model.access_mode = app_setting.access_mode@@ -1002,7 +1002,7 @@ class AppCopyApi(Resource):session.commit()# Inherit web app permission from original app- if result.app_id and FeatureService.get_system_features().webapp_auth.enabled:+ if result.app_id and SystemFeatureService.is_webapp_auth_enabled():try:# Get the original app's access modeoriginal_settings = EnterpriseService.WebAppAuth.get_app_access_mode_by_id(app_model.id)diff --git a/api/controllers/console/app/app_import.py b/api/controllers/console/app/app_import.pyindex f2d3bace841..f8fa63a7fba 100644--- a/api/controllers/console/app/app_import.py+++ b/api/controllers/console/app/app_import.py@@ -31,7 +31,7 @@ from services.app_dsl_service import (from services.enterprise.enterprise_service import EnterpriseServicefrom services.entities.dsl_entities import CheckDependenciesResult, ImportStatusfrom services.errors.account import NoPermissionError-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServicefrom .. import console_nsfrom .permission_keys import get_app_permission_keys@@ -127,7 +127,7 @@ class AppImportApi(Resource):result.app_id,)- if result.app_id and FeatureService.get_system_features().webapp_auth.enabled:+ if result.app_id and SystemFeatureService.is_webapp_auth_enabled():# update web app setting as privateEnterpriseService.WebAppAuth.update_app_access_mode(result.app_id, "private")# Return appropriate status code based on resultdiff --git a/api/controllers/console/auth/forgot_password.py b/api/controllers/console/auth/forgot_password.pyindex 9a8784d543a..a4d6bc4a090 100644--- a/api/controllers/console/auth/forgot_password.py+++ b/api/controllers/console/auth/forgot_password.py@@ -25,7 +25,7 @@ from services.entities.auth_entities import (ForgotPasswordResetPayload,ForgotPasswordSendPayload,)-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServiceclass ForgotPasswordEmailResponse(BaseModel):@@ -87,7 +87,7 @@ class ForgotPasswordSendEmailApi(Resource):account=account,email=normalized_email,language=language,- is_allow_register=FeatureService.get_system_features().is_allow_register,+ is_allow_register=SystemFeatureService.is_registration_allowed(),)return {"result": "success", "data": token}@@ -198,6 +198,6 @@ class ForgotPasswordResetApi(Resource):# Create workspace if neededif (not TenantService.get_join_tenants(account, session=db.session())- and FeatureService.is_workspace_creation_allowed()+ and SystemFeatureService.is_workspace_creation_allowed()):TenantService.create_owner_tenant(account, session=db.session())diff --git a/api/controllers/console/auth/login.py b/api/controllers/console/auth/login.pyindex 14b51df7dcc..4a06243877c 100644--- a/api/controllers/console/auth/login.py+++ b/api/controllers/console/auth/login.py@@ -81,7 +81,7 @@ from services.errors.account import (EmailDomainSuspendedError as EmailDomainSuspendedRegistrationError,)from services.errors.workspace import WorkSpaceNotAllowedCreateError, WorkspacesLimitExceededError-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServicefrom services.turnstile_service import (EMAIL_CODE_VERIFY_ACTION,TurnstileChallengeRejectedError,@@ -201,8 +201,8 @@ class LoginApi(Resource):tenants = TenantService.get_join_tenants(account, session=db.session())if len(tenants) == 0:if (- FeatureService.is_workspace_creation_allowed()- and not FeatureService.get_license().workspaces.is_available()+ SystemFeatureService.is_workspace_creation_allowed()+ and not SystemFeatureService.get_license().workspaces.is_available()):raise WorkspacesLimitExceeded()else:@@ -272,7 +272,7 @@ class ResetPasswordSendEmailApi(Resource):email=normalized_email,account=account,language=language,- is_allow_register=FeatureService.get_system_features().is_allow_register,+ is_allow_register=SystemFeatureService.is_registration_allowed(),)return SimpleResultDataResponse(result="success", data=token).model_dump(mode="json")@@ -313,7 +313,7 @@ class EmailCodeLoginSendEmailApi(Resource):raise AccountInFreezeError() from excif account is None:- if FeatureService.get_system_features().is_allow_register:+ if SystemFeatureService.is_registration_allowed():token = AccountService.send_email_code_login_email(email=normalized_email, language=language)else:raise AccountNotFound()@@ -398,10 +398,10 @@ class EmailCodeLoginApi(Resource):if account:tenants = TenantService.get_join_tenants(account, session=db.session())if not tenants:- workspaces = FeatureService.get_license().workspaces+ workspaces = SystemFeatureService.get_license().workspacesif not workspaces.is_available():raise WorkspacesLimitExceeded()- if not FeatureService.is_workspace_creation_allowed():+ if not SystemFeatureService.is_workspace_creation_allowed():raise NotAllowedCreateWorkspace()else:TenantService.create_owner_tenant(account, session=db.session())diff --git a/api/controllers/console/auth/oauth.py b/api/controllers/console/auth/oauth.pyindex e7cc10c9e06..58f13f33511 100644--- a/api/controllers/console/auth/oauth.py+++ b/api/controllers/console/auth/oauth.py@@ -36,7 +36,7 @@ from services.errors.account import (EmailDomainSuspendedError as EmailDomainSuspendedRegistrationError,)from services.errors.workspace import WorkSpaceNotAllowedCreateError, WorkSpaceNotFoundError-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServicefrom .. import console_ns@@ -310,7 +310,7 @@ def _generate_account(if account:tenants = TenantService.get_join_tenants(account, session=db.session())if not tenants:- if not FeatureService.is_workspace_creation_allowed():+ if not SystemFeatureService.is_workspace_creation_allowed():raise WorkSpaceNotAllowedCreateError()else:TenantService.create_owner_tenant(account, session=db.session())@@ -318,7 +318,7 @@ def _generate_account(if not account:normalized_email = user_info.email.lower()oauth_new_user = True- if not FeatureService.get_system_features().is_allow_register:+ if not SystemFeatureService.is_registration_allowed():if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:freeze_type = BillingService.get_email_freeze_type(normalized_email)if freeze_type:diff --git a/api/controllers/console/explore/wraps.py b/api/controllers/console/explore/wraps.pyindex a09341f649d..872c48538c3 100644--- a/api/controllers/console/explore/wraps.py+++ b/api/controllers/console/explore/wraps.py@@ -18,7 +18,7 @@ from extensions.ext_database import dbfrom libs.login import current_account_with_tenant, login_requiredfrom models import AccountTrialAppRecord, App, InstalledApp, TrialAppfrom services.enterprise.enterprise_service import EnterpriseService-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServicedef installed_app_required[**P, R](view: Callable[Concatenate[InstalledApp, P], R] | None = None):@@ -55,8 +55,7 @@ def user_allowed_to_access_app[**P, R](view: Callable[Concatenate[InstalledApp,@wraps(view)def decorated(installed_app: InstalledApp, *args: P.args, **kwargs: P.kwargs):current_user, _ = current_account_with_tenant()- feature = FeatureService.get_system_features()- if feature.webapp_auth.enabled:+ if SystemFeatureService.is_webapp_auth_enabled():app_id = installed_app.app_idres = EnterpriseService.WebAppAuth.is_user_allowed_to_access_webapp(user_id=str(current_user.id),diff --git a/api/controllers/console/feature.py b/api/controllers/console/feature.pyindex edc9a9f19ab..c735420c476 100644--- a/api/controllers/console/feature.py+++ b/api/controllers/console/feature.py@@ -125,7 +125,7 @@ class SystemFeatureApi(Resource):Authentication configuration must be available before the authentication flow can be selected.Authenticated license detail is served separately by SystemFeatureLicenseApi."""- return dump_response(SystemFeatureModel, application_services().feature_queries.get_system_features())+ return dump_response(SystemFeatureModel, application_services().feature_queries.get_public_system_features())@console_ns.route("/system-features/license")diff --git a/api/controllers/console/flask_admission.py b/api/controllers/console/flask_admission.pyindex eb300128aed..7181de23839 100644--- a/api/controllers/console/flask_admission.py+++ b/api/controllers/console/flask_admission.py@@ -22,7 +22,7 @@ from libs.login import current_account_with_tenant, login_requiredfrom machinery.context import RequestContextfrom machinery.errors import AdmissionConfigurationErrorfrom models.account import TenantAccountRole-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServicedef console_email_registration_admission[T, **P, R](@@ -32,8 +32,10 @@ def console_email_registration_admission[T, **P, R](@wraps(view)def check_registration_features(self: T, /, *args: P.args, **kwargs: P.kwargs) -> R:- features = FeatureService.get_system_features()- if not features.enable_email_password_login or not features.is_allow_register:+ if (+ not SystemFeatureService.is_email_password_login_enabled()+ or not SystemFeatureService.is_registration_allowed()+ ):abort(403)return view(self, *args, **kwargs)diff --git a/api/controllers/console/workspace/members.py b/api/controllers/console/workspace/members.pyindex ebc30c9fa59..f32bc47cc42 100644--- a/api/controllers/console/workspace/members.py+++ b/api/controllers/console/workspace/members.py@@ -45,6 +45,7 @@ from models.account import Account, TenantAccountJoin, TenantAccountRolefrom services.account_service import AccountService, RegisterService, TenantServicefrom services.errors.account import AccountAlreadyInTenantErrorfrom services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServiceclass MemberInvitePayload(BaseModel):@@ -185,7 +186,7 @@ def _check_member_invite_limits(tenant_id: str, new_member_count: int, new_accouif workspace_members.enabled is True and not workspace_members.is_available(new_member_count):raise WorkspaceMembersLimitExceeded()if new_account_count > 0:- seats = FeatureService.get_license().seats+ seats = SystemFeatureService.get_license().seatsif not seats.is_available(new_account_count):raise SeatsLimitExceeded()returndiff --git a/api/controllers/console/wraps.py b/api/controllers/console/wraps.pyindex da1d5584af6..dd681a3b5e5 100644--- a/api/controllers/console/wraps.py+++ b/api/controllers/console/wraps.py@@ -19,6 +19,7 @@ from controllers.common.wraps import (from controllers.console.auth.error import AuthenticationFailedError, EmailCodeErrorfrom controllers.console.workspace.error import AccountNotInitializedErrorfrom enums import CloudPlan, DeploymentEdition+from extensions.ext_application_services import application_servicesfrom extensions.ext_database import dbfrom extensions.ext_redis import redis_clientfrom libs.encryption import FieldEncryption@@ -31,6 +32,7 @@ from services.billing_service import BillingServicefrom services.entities.feature_entities import LicenseStatusfrom services.feature_service import FeatureServicefrom services.operation_service import OperationService, UtmInfo+from services.system_feature_service import SystemFeatureServicefrom .error import NotInitValidateError, NotSetupError, UnauthorizedAndForceLogout@@ -183,7 +185,7 @@ def cloud_edition_billing_resource_check[**P, R](resource: str) -> Callable[[Calif dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:return view(*args, **kwargs)- vector_space = FeatureService.get_vector_space(current_tenant_id)+ vector_space = application_services().feature_queries.get_workspace_vector_space(current_tenant_id)if 0 < vector_space.limit <= vector_space.size:abort(403,@@ -330,8 +332,11 @@ def setup_required[R](view: Callable[..., R]) -> Callable[..., R]:def enterprise_license_required[**P, R](view: Callable[P, R]) -> Callable[P, R]:@wraps(view)def decorated(*args: P.args, **kwargs: P.kwargs):- settings = FeatureService.get_system_features()- if settings.license.status in [LicenseStatus.INACTIVE, LicenseStatus.EXPIRED, LicenseStatus.LOST]:+ if SystemFeatureService.get_license_status() in [+ LicenseStatus.INACTIVE,+ LicenseStatus.EXPIRED,+ LicenseStatus.LOST,+ ]:raise UnauthorizedAndForceLogout("Your license is invalid. Please contact your administrator.")return view(*args, **kwargs)@@ -342,8 +347,7 @@ def enterprise_license_required[**P, R](view: Callable[P, R]) -> Callable[P, R]:def email_password_login_enabled[**P, R](view: Callable[P, R]) -> Callable[P, R]:@wraps(view)def decorated(*args: P.args, **kwargs: P.kwargs):- features = FeatureService.get_system_features()- if features.enable_email_password_login:+ if SystemFeatureService.is_email_password_login_enabled():return view(*args, **kwargs)# otherwise, return 403@@ -355,8 +359,7 @@ def email_password_login_enabled[**P, R](view: Callable[P, R]) -> Callable[P, R]def enable_change_email[**P, R](view: Callable[P, R]) -> Callable[P, R]:@wraps(view)def decorated(*args: P.args, **kwargs: P.kwargs):- features = FeatureService.get_system_features()- if features.enable_change_email:+ if SystemFeatureService.is_change_email_enabled():return view(*args, **kwargs)# otherwise, return 403@@ -372,7 +375,11 @@ def is_allow_transfer_owner[**P, R](view: Callable[P, R]) -> Callable[P, R]:_, current_tenant_id = current_account_with_tenant()# Check both billing/plan level and workspace policy level permissions- check_workspace_owner_transfer_permission(current_tenant_id)+ features = application_services().feature_queries.get_workspace_features(current_tenant_id)+ check_workspace_owner_transfer_permission(+ current_tenant_id,+ owner_transfer_allowed=features.is_allow_transfer_workspace,+ )return view(*args, **kwargs)return decorateddiff --git a/api/controllers/inner_api/mail.py b/api/controllers/inner_api/mail.pyindex 885ab7b78d4..353cfc9dda5 100644--- a/api/controllers/inner_api/mail.py+++ b/api/controllers/inner_api/mail.py@@ -6,8 +6,9 @@ from pydantic import BaseModel, Fieldfrom controllers.common.schema import register_schema_modelfrom controllers.console.wraps import setup_requiredfrom controllers.inner_api import inner_api_ns-from controllers.inner_api.wraps import billing_inner_api_only, enterprise_inner_api_only-from tasks.mail_inner_task import send_inner_email_task+from controllers.inner_api.wraps import inner_api_only+from extensions.ext_application_services import application_services+from services.entities.mail_entities import InnerMailMessageclass InnerMailPayload(BaseModel):@@ -28,25 +29,27 @@ class BaseMail(Resource):@inner_api_ns.expect(inner_api_ns.models[InnerMailPayload.__name__])def post(self):args = InnerMailPayload.model_validate(inner_api_ns.payload or {})- send_inner_email_task.delay(- to=args.to,- subject=args.subject,- body=args.body,- substitutions=args.substitutions, # type: ignore+ application_services().inner_mail.send(+ InnerMailMessage(+ recipients=tuple(args.to),+ subject=args.subject,+ body=args.body,+ substitutions=args.substitutions,+ ))return {"message": "success"}, 200@inner_api_ns.route("/enterprise/mail")class EnterpriseMail(BaseMail):- method_decorators = [setup_required, enterprise_inner_api_only]-@inner_api_ns.doc("send_enterprise_mail")@inner_api_ns.doc(description="Send internal email for enterprise features")@inner_api_ns.expect(inner_api_ns.models[InnerMailPayload.__name__])@inner_api_ns.doc(responses={200: "Email sent successfully", 401: "Unauthorized - invalid API key", 404: "Service not available"})+ @inner_api_only+ @setup_requireddef post(self):"""Send internal email for enterprise features.@@ -61,14 +64,14 @@ class EnterpriseMail(BaseMail):@inner_api_ns.route("/billing/mail")class BillingMail(BaseMail):- method_decorators = [setup_required, billing_inner_api_only]-@inner_api_ns.doc("send_billing_mail")@inner_api_ns.doc(description="Send internal email for billing notifications")@inner_api_ns.expect(inner_api_ns.models[InnerMailPayload.__name__])@inner_api_ns.doc(responses={200: "Email sent successfully", 401: "Unauthorized - invalid API key", 404: "Service not available"})+ @inner_api_only+ @setup_requireddef post(self):"""Send internal email for billing notifications.diff --git a/api/controllers/inner_api/wraps.py b/api/controllers/inner_api/wraps.pyindex 5ddb55aaa3f..241660291ab 100644--- a/api/controllers/inner_api/wraps.py+++ b/api/controllers/inner_api/wraps.py@@ -35,10 +35,6 @@ def inner_api_only[**P, R](view: Callable[P, R]) -> Callable[P, R]:return decorated-def billing_inner_api_only[**P, R](view: Callable[P, R]) -> Callable[P, R]:- return inner_api_only(view)--def enterprise_inner_api_only[**P, R](view: Callable[P, R]) -> Callable[P, R]:return inner_api_only(view)diff --git a/api/controllers/openapi/auth/conditions.py b/api/controllers/openapi/auth/conditions.pyindex a25eaf78aa1..49da949ccab 100644--- a/api/controllers/openapi/auth/conditions.py+++ b/api/controllers/openapi/auth/conditions.py@@ -7,7 +7,7 @@ from controllers.openapi.auth.data import AuthData, RequestContextfrom enums import DeploymentEditionfrom libs.oauth_bearer import Scope, TokenTypefrom services.enterprise.enterprise_service import WebAppAccessMode-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServiceCondFn = Callable[[RequestContext, AuthData | None], bool]@@ -50,7 +50,7 @@ EDITION_COMMUNITY = config_cond(lambda: dify_config.DEPLOYMENT_EDITION == DeployEDITION_ENTERPRISE = config_cond(lambda: dify_config.DEPLOYMENT_EDITION == DeploymentEdition.ENTERPRISE)EDITION_CLOUD = config_cond(lambda: dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD)-WEBAPP_AUTH_ENABLED = config_cond(lambda: FeatureService.get_system_features().webapp_auth.enabled)+WEBAPP_AUTH_ENABLED = config_cond(lambda: SystemFeatureService.is_webapp_auth_enabled())WEBAPP_RUN_SCOPED = request_cond(lambda ctx: ctx.scope == Scope.APPS_RUN)diff --git a/api/controllers/openapi/auth/pipeline.py b/api/controllers/openapi/auth/pipeline.pyindex f27064eda96..6a68e5c91fe 100644--- a/api/controllers/openapi/auth/pipeline.py+++ b/api/controllers/openapi/auth/pipeline.py@@ -37,7 +37,7 @@ from libs.oauth_bearer import ()from models.account import TenantAccountRolefrom services.entities.feature_entities import LicenseStatus-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServiceclass AuthPipeline:@@ -265,8 +265,11 @@ def _subject_type_str(identity: Any) -> str | None:def _check_license() -> None:- settings = FeatureService.get_system_features()- if settings.license.status in {LicenseStatus.INACTIVE, LicenseStatus.EXPIRED, LicenseStatus.LOST}:+ if SystemFeatureService.get_license_status() in {+ LicenseStatus.INACTIVE,+ LicenseStatus.EXPIRED,+ LicenseStatus.LOST,+ }:raise Forbidden("license_invalid")diff --git a/api/controllers/service_api/wraps.py b/api/controllers/service_api/wraps.pyindex 09ce95942dd..88d865def14 100644--- a/api/controllers/service_api/wraps.py+++ b/api/controllers/service_api/wraps.py@@ -23,6 +23,7 @@ from controllers.service_api.schema import (USER_REQUIRED_ATTR,)from enums import CloudPlan, DeploymentEdition+from extensions.ext_application_services import application_servicesfrom extensions.ext_database import dbfrom extensions.ext_redis import redis_clientfrom libs.login import current_user@@ -196,7 +197,7 @@ def cloud_edition_billing_resource_check[**P, R](if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:return view(*args, **kwargs)- vector_space = FeatureService.get_vector_space(api_token.tenant_id)+ vector_space = application_services().feature_queries.get_workspace_vector_space(api_token.tenant_id)if vector_space.usage_unknown:features = FeatureService.get_features(api_token.tenant_id, exclude_vector_space=True)if features.billing.enabled and features.billing.subscription.plan == CloudPlan.SANDBOX:diff --git a/api/controllers/web/feature.py b/api/controllers/web/feature.pyindex fcaaac98e28..6e07d9470cd 100644--- a/api/controllers/web/feature.py+++ b/api/controllers/web/feature.py@@ -32,5 +32,5 @@ class SystemFeatureApi(Resource):"""return dump_response(SystemFeatureModel,- application_services().feature_queries.get_system_features(),+ application_services().feature_queries.get_public_system_features(),)diff --git a/api/controllers/web/passport.py b/api/controllers/web/passport.pyindex 4b0b25fb971..3e4a7960984 100644--- a/api/controllers/web/passport.py+++ b/api/controllers/web/passport.py@@ -1,27 +1,22 @@-import uuid-from datetime import UTC, datetime, timedelta-from typing import Any-from flask import requestfrom flask_restx import Resourcefrom pydantic import BaseModel, Field-from sqlalchemy import func, selectfrom werkzeug.exceptions import NotFound, Unauthorized-from configs import dify_configfrom constants import HEADER_NAME_APP_CODEfrom controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_modelsfrom controllers.web import web_nsfrom controllers.web.error import WebAppAuthRequiredError-from extensions.ext_database import db+from extensions.ext_application_services import application_servicesfrom fields.base import ResponseModelfrom libs.helper import dump_response-from libs.passport import PassportServicefrom libs.token import extract_webapp_access_token-from models.enums import EndUserType-from models.model import App, EndUser, Site-from services.feature_service import FeatureService-from services.webapp_auth_service import WebAppAuthService, WebAppAuthType+from services.entities.passport_entities import WebPassportRequest+from services.web_passport_service import (+ WebPassportAuthenticationRequiredError,+ WebPassportNotFoundError,+ WebPassportUnauthorizedError,+)class PassportQuery(BaseModel):@@ -40,7 +35,7 @@ register_response_schema_models(web_ns, PassportAccessTokenResponse)@web_ns.route("/passport")class PassportResource(Resource):- """Base resource for passport."""+ """Issue an authentication passport for a deployed web application."""@web_ns.doc("get_passport")@web_ns.doc(description="Get authentication passport for web application access")@@ -54,207 +49,23 @@ class PassportResource(Resource):)@web_ns.response(200, "Passport retrieved successfully", web_ns.models[PassportAccessTokenResponse.__name__])def get(self):- system_features = FeatureService.get_system_features()app_code = request.headers.get(HEADER_NAME_APP_CODE)- user_id = request.args.get("user_id")- access_token = extract_webapp_access_token(request)if app_code is None:raise Unauthorized("X-App-Code header is missing.")- if system_features.webapp_auth.enabled:- enterprise_user_decoded = decode_enterprise_webapp_user_id(access_token)- app_auth_type = WebAppAuthService.get_app_auth_type(app_code=app_code, session=db.session())- if app_auth_type != WebAppAuthType.PUBLIC:- if not enterprise_user_decoded:- raise WebAppAuthRequiredError()- return dump_response(- PassportAccessTokenResponse,- exchange_token_for_existing_web_user(- app_code=app_code, enterprise_user_decoded=enterprise_user_decoded, auth_type=app_auth_type- ),- )-- # get site from db and check if it is normal- site = db.session.scalar(select(Site).where(Site.code == app_code, Site.status == "normal"))- if not site:- raise NotFound()- # get app from db and check if it is normal and enable_site- app_model = db.session.scalar(select(App).where(App.id == site.app_id))- if not app_model or app_model.status != "normal" or not app_model.enable_site:- raise NotFound()-- if user_id:- end_user = db.session.scalar(- select(EndUser).where(EndUser.app_id == app_model.id, EndUser.session_id == user_id)- )-- if end_user:- pass- else:- end_user = EndUser(- tenant_id=app_model.tenant_id,- app_id=app_model.id,- type=EndUserType.BROWSER,- is_anonymous=True,- session_id=user_id,- )- db.session.add(end_user)- db.session.commit()- else:- end_user = EndUser(- tenant_id=app_model.tenant_id,- app_id=app_model.id,- type=EndUserType.BROWSER,- is_anonymous=True,- session_id=generate_session_id(),- )- db.session.add(end_user)- db.session.commit()-- payload = {- "iss": site.app_id,- "sub": "Web API Passport",- "app_id": site.app_id,- "app_code": app_code,- "end_user_id": end_user.id,- }-- tk = PassportService().issue(payload)-- return dump_response(PassportAccessTokenResponse, {"access_token": tk})---def decode_enterprise_webapp_user_id(jwt_token: str | None) -> dict[str, Any] | None:- """- Decode the enterprise user session from the Authorization header.- """- if not jwt_token:- return None-- decoded: dict[str, Any] = PassportService().verify(jwt_token)- source = decoded.get("token_source")- if not source or source != "webapp_login_token":- raise Unauthorized("Invalid token source. Expected 'webapp_login_token'.")- return decoded---def exchange_token_for_existing_web_user(- app_code: str, enterprise_user_decoded: dict[str, Any], auth_type: WebAppAuthType-):- """- Exchange a token for an existing web user session.- """- user_id = enterprise_user_decoded.get("user_id")- end_user_id = enterprise_user_decoded.get("end_user_id")- session_id = enterprise_user_decoded.get("session_id")- user_auth_type = enterprise_user_decoded.get("auth_type")- exchanged_token_expires_unix = enterprise_user_decoded.get("exp")-- if not user_auth_type:- raise Unauthorized("Missing auth_type in the token.")-- site = db.session.scalar(select(Site).where(Site.code == app_code, Site.status == "normal"))- if not site:- raise NotFound()-- app_model = db.session.scalar(select(App).where(App.id == site.app_id))- if not app_model or app_model.status != "normal" or not app_model.enable_site:- raise NotFound()-- match auth_type:- case WebAppAuthType.PUBLIC:- return _exchange_for_public_app_token(app_model, site, enterprise_user_decoded)- case WebAppAuthType.EXTERNAL:- if user_auth_type != "external":- raise WebAppAuthRequiredError("Please login as external user.")- case WebAppAuthType.INTERNAL:- if user_auth_type != "internal":- raise WebAppAuthRequiredError("Please login as internal user.")-- end_user = None- if end_user_id:- end_user = db.session.scalar(select(EndUser).where(EndUser.id == end_user_id))- if session_id:- end_user = db.session.scalar(- select(EndUser).where(- EndUser.session_id == session_id,- EndUser.tenant_id == app_model.tenant_id,- EndUser.app_id == app_model.id,- )- )- if not end_user:- if not session_id:- raise NotFound("Missing session_id for existing web user.")- end_user = EndUser(- tenant_id=app_model.tenant_id,- app_id=app_model.id,- type=EndUserType.BROWSER,- is_anonymous=True,- session_id=session_id,- )- db.session.add(end_user)- db.session.commit()-- exp = int((datetime.now(UTC) + timedelta(minutes=dify_config.ACCESS_TOKEN_EXPIRE_MINUTES)).timestamp())- if exchanged_token_expires_unix:- exp = int(exchanged_token_expires_unix)-- payload = {- "iss": site.id,- "sub": "Web API Passport",- "app_id": site.app_id,- "app_code": site.code,- "user_id": user_id,- "end_user_id": end_user.id,- "auth_type": user_auth_type,- "granted_at": int(datetime.now(UTC).timestamp()),- "token_source": "webapp",- "exp": exp,- }- token: str = PassportService().issue(payload)- return {"access_token": token}---def _exchange_for_public_app_token(app_model, site, token_decoded):- user_id = token_decoded.get("user_id")- end_user = None- if user_id:- end_user = db.session.scalar(- select(EndUser).where(EndUser.app_id == app_model.id, EndUser.session_id == user_id)- )-- if not end_user:- end_user = EndUser(- tenant_id=app_model.tenant_id,- app_id=app_model.id,- type=EndUserType.BROWSER,- is_anonymous=True,- session_id=generate_session_id(),- )-- db.session.add(end_user)- db.session.commit()-- payload = {- "iss": site.app_id,- "sub": "Web API Passport",- "app_id": site.app_id,- "app_code": site.code,- "end_user_id": end_user.id,- }-- tk = PassportService().issue(payload)-- return {"access_token": tk}--def generate_session_id():- """- Generate a unique session ID.- """- while True:- session_id = str(uuid.uuid4())- existing_count = db.session.scalar(- select(func.count()).select_from(EndUser).where(EndUser.session_id == session_id)+ query = PassportQuery.model_validate(request.args.to_dict(flat=True))+ passport_request = WebPassportRequest(+ app_code=app_code,+ user_session_id=query.user_id,+ access_token=extract_webapp_access_token(request),)- if existing_count == 0:- return session_id+ try:+ result = application_services().web_passport.issue(passport_request)+ except WebPassportAuthenticationRequiredError as exc:+ raise WebAppAuthRequiredError(str(exc)) from exc+ except WebPassportUnauthorizedError as exc:+ raise Unauthorized(str(exc)) from exc+ except WebPassportNotFoundError as exc:+ raise NotFound(str(exc) or None) from exc++ return dump_response(PassportAccessTokenResponse, {"access_token": result.access_token})diff --git a/api/controllers/web/wraps.py b/api/controllers/web/wraps.pyindex cf2da497176..69e0edb059f 100644--- a/api/controllers/web/wraps.py+++ b/api/controllers/web/wraps.py@@ -18,7 +18,7 @@ from libs.token import extract_webapp_passportfrom models.model import App, EndUser, Sitefrom services.app_service import AppServicefrom services.enterprise.enterprise_service import EnterpriseService, WebAppAccessMode, WebAppSettings-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServicefrom services.webapp_auth_service import WebAppAuthService@@ -44,7 +44,7 @@ def validate_jwt_token[**P, R](def decode_jwt_token(app_code: str | None = None, user_id: str | None = None) -> tuple[App, EndUser]:- system_features = FeatureService.get_system_features()+ webapp_auth_enabled = SystemFeatureService.is_webapp_auth_enabled()if not app_code:app_code = str(request.headers.get(HEADER_NAME_APP_CODE))try:@@ -75,21 +75,19 @@ def decode_jwt_token(app_code: str | None = None, user_id: str | None = None) -># for enterprise webapp authapp_web_auth_enabled = Falsewebapp_settings = None- if system_features.webapp_auth.enabled:+ if webapp_auth_enabled:app_id = AppService.get_app_id_by_code(app_code, session=db.session())webapp_settings = EnterpriseService.WebAppAuth.get_app_access_mode_by_id(app_id)if not webapp_settings:raise NotFound("Web app settings not found.")app_web_auth_enabled = webapp_settings.access_mode != WebAppAccessMode.PUBLIC- _validate_webapp_token(decoded, app_web_auth_enabled, system_features.webapp_auth.enabled)- _validate_user_accessibility(- decoded, app_code, app_web_auth_enabled, system_features.webapp_auth.enabled, webapp_settings- )+ _validate_webapp_token(decoded, app_web_auth_enabled, webapp_auth_enabled)+ _validate_user_accessibility(decoded, app_code, app_web_auth_enabled, webapp_auth_enabled, webapp_settings)return app_model, end_userexcept Unauthorized as e:- if system_features.webapp_auth.enabled:+ if webapp_auth_enabled:if not app_code:raise Unauthorized("Please re-login to access the web app.")app_id = AppService.get_app_id_by_code(app_code, session=db.session())diff --git a/api/core/helper/credential_utils.py b/api/core/helper/credential_utils.pyindex 19a62c43766..6fce1058dea 100644--- a/api/core/helper/credential_utils.py+++ b/api/core/helper/credential_utils.py@@ -69,9 +69,9 @@ def check_credential_policy_compliance(CheckCredentialPolicyComplianceRequest,PluginManagerService,)- from services.feature_service import FeatureService+ from services.system_feature_service import SystemFeatureService- if not FeatureService.is_plugin_manager_enabled() or not credential_id:+ if not SystemFeatureService.is_plugin_manager_enabled() or not credential_id:return# Check if credential exists in database first (if requested)diff --git a/api/core/plugin/plugin_service.py b/api/core/plugin/plugin_service.pyindex 0fdfd4d27b3..3a9f72483f5 100644--- a/api/core/plugin/plugin_service.py+++ b/api/core/plugin/plugin_service.py@@ -69,7 +69,7 @@ from services.enterprise.plugin_manager_service import ()from services.entities.feature_entities import PluginInstallationPermissionModel, PluginInstallationScopefrom services.errors.plugin import PluginInstallationForbiddenError-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServicelogger = logging.getLogger(__name__)_provider_entities_adapter: TypeAdapter[list[PluginModelProviderDeclaration]] = TypeAdapter(@@ -667,7 +667,7 @@ class PluginService:@staticmethoddef _get_plugin_installation_permission() -> PluginInstallationPermissionModel:"""Resolve the validated policy and reject deny-all before any installation side effect."""- permission = FeatureService.get_plugin_installation_permission()+ permission = SystemFeatureService.get_plugin_installation_permission()if permission.plugin_installation_scope == PluginInstallationScope.NONE:raise PluginInstallationForbiddenError("Installing plugins is not allowed")return permissiondiff --git a/api/extensions/ext_application_services.py b/api/extensions/ext_application_services.pyindex 747c658a561..ef2cce70e87 100644--- a/api/extensions/ext_application_services.py+++ b/api/extensions/ext_application_services.py@@ -3,7 +3,9 @@import jsonfrom collections.abc import Mappingfrom dataclasses import dataclass+from datetime import UTC, datetimefrom typing import cast+from uuid import uuid4import httpxfrom flask import Flask, current_app@@ -19,6 +21,7 @@ from enums import DeploymentEdition, WebAppAccessModefrom extensions.ext_redis import RedisClientWrapper, redis_clientfrom libs.datetime_utils import naive_utc_nowfrom libs.helper import RateLimiter+from libs.passport import PassportServicefrom repositories.account_activation_repository import SQLAlchemyAccountActivationRepositoryfrom repositories.account_integration_repository import SQLAlchemyAccountIntegrationRepositoryfrom repositories.account_repository import SQLAlchemyAccountRepository@@ -35,6 +38,7 @@ from repositories.step_by_step_tour_repository import SQLAlchemyStepByStepTourStfrom repositories.tag_repository import TagRepositoryfrom repositories.trial_app_query_repository import TrialAppQueryRepositoryfrom repositories.trial_app_usage_repository import TrialAppUsageRepository+from repositories.web_passport_repository import WebPassportRepositoryfrom repositories.webapp_access_query_repository import WebAppAccessQueryRepositoryfrom repositories.workflow_run_archive_repository import WorkflowRunArchiveBundleQueryRepositoryfrom repositories.workspace_member_query_repository import WorkspaceMemberQueryRepository@@ -101,10 +105,10 @@ from services.enterprise.enterprise_service import EnterpriseServicefrom services.errors.enterprise import EnterpriseServiceErrorfrom services.explore_banner_query_service import ExploreBannerQueryServicefrom services.feature_query_service import FeatureQueryService-from services.feature_service import FeatureServicefrom services.feature_service_gateway import FeatureServiceGatewayfrom services.file_service import FileServicefrom services.init_validation_service import InitValidationService+from services.inner_mail_service import InnerMailServicefrom services.notification_gateway import BillingNotificationGatewayfrom services.notification_service import NotificationServicefrom services.notion_data_source_gateway import NotionDataSourceGateway@@ -126,9 +130,15 @@ from services.schema_definition_service import SchemaDefinitionServicefrom services.setup_adapters import RedisSetupLock, RegisterServiceAccountProvisionerfrom services.setup_service import SetupServicefrom services.step_by_step_tour_service import StepByStepTourService+from services.system_feature_service import SystemFeatureServicefrom services.tag_application_service import TagApplicationServicefrom services.trial_app_usage import TrialAppUsageRecorderfrom services.web_app_runtime_query_service import WebAppRuntimeQueryService+from services.web_passport_gateways import (+ DeploymentWebPassportAuthGateway,+ PassportTokenGateway,+)+from services.web_passport_service import WebPassportServicefrom services.webapp_access_query_service import (WebAppAccessQueryService,WebAppAccessUnavailableError,@@ -138,6 +148,7 @@ from services.workspace_member_query_service import WorkspaceMemberQueryServicefrom services.workspace_member_role_resolver import DeploymentWorkspaceMemberRoleResolverfrom services.workspace_plan_gateway import DeploymentWorkspacePlanGatewayfrom services.workspace_query_service import WorkspaceQueryService+from tasks.mail_inner_task import enqueue_inner_mail_EXTENSION_KEY = "application_services"@@ -200,6 +211,8 @@ class ApplicationServices:workflow_run_archives: WorkflowRunArchiveServiceworkspace_queries: WorkspaceQueryServiceworkspace_member_queries: WorkspaceMemberQueryService+ inner_mail: InnerMailService+ web_passport: WebPassportServicetags: TagApplicationServiceworkflow_statistics: WorkflowStatisticQueryService@@ -257,7 +270,7 @@ def build_application_services(feature_gateway = FeatureServiceGateway()accounts = SQLAlchemyAccountRepository(session_factory=database_client)integrations = SQLAlchemyAccountIntegrationRepository(session_factory=database_client)- trial_app_enabled = FeatureService.is_trial_app_enabled()+ trial_app_enabled = SystemFeatureService.is_trial_app_enabled()database_catalog = DatabaseRecommendedAppCatalogRepository(session_factory=database_client, redis=redis)builtin_catalog = BuiltinRecommendedAppCatalogGateway()remote_catalog = RemoteRecommendedAppCatalogGateway()@@ -409,7 +422,7 @@ def build_application_services(data_source_oauth=_build_data_source_oauth_services(database_client=database_client),webapp_access=WebAppAccessQueryService(access=WebAppAccessQueryRepository(session_factory=database_client),- webapp_auth_enabled=FeatureService.is_webapp_auth_enabled(),+ webapp_auth_enabled=SystemFeatureService.is_webapp_auth_enabled(deployment_edition=deployment_edition),access_mode_for_app=_get_enterprise_webapp_access_mode,is_user_allowed_for_app=_is_user_allowed_to_access_webapp,),@@ -421,7 +434,7 @@ def build_application_services(),explore_banner_queries=ExploreBannerQueryService(banners=ExploreBannerQueryRepository(session_factory=database_client),- enabled=FeatureService.is_explore_banner_enabled(),+ enabled=SystemFeatureService.is_explore_banner_enabled(),),schema_definitions=SchemaDefinitionService(source_factory=SchemaManager),setup=SetupService(@@ -475,6 +488,20 @@ def build_application_services(),roles=DeploymentWorkspaceMemberRoleResolver(),),+ inner_mail=InnerMailService(dispatch=enqueue_inner_mail),+ web_passport=WebPassportService(+ passports=WebPassportRepository(+ session_factory=database_client,+ generate_session_id=lambda: str(uuid4()),+ ),+ auth=DeploymentWebPassportAuthGateway(+ webapp_auth_enabled=SystemFeatureService.is_webapp_auth_enabled(deployment_edition=deployment_edition),+ get_app_access_mode=EnterpriseService.WebAppAuth.get_app_access_mode_by_id,+ ),+ tokens=PassportTokenGateway(passport=PassportService()),+ now=lambda: datetime.now(UTC),+ access_token_expire_minutes=dify_config.ACCESS_TOKEN_EXPIRE_MINUTES,+ ),tags=TagApplicationService(tags=TagRepository(session_factory=database_client),),diff --git a/api/libs/device_flow_security.py b/api/libs/device_flow_security.pyindex c10d3daaab6..1e7ec3683c3 100644--- a/api/libs/device_flow_security.py+++ b/api/libs/device_flow_security.py@@ -18,7 +18,7 @@ from werkzeug.exceptions import NotFoundfrom libs import jwsfrom libs.token import is_securefrom services.entities.feature_entities import LicenseStatus-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServicelogger = logging.getLogger(__name__)@@ -40,8 +40,7 @@ def enterprise_only[**P, R](view: Callable[P, R]) -> Callable[P, R]:@wraps(view)def decorated(*args: P.args, **kwargs: P.kwargs):- settings = FeatureService.get_system_features()- if settings.license.status not in _EE_ENABLED_STATUSES:+ if SystemFeatureService.get_license_status() not in _EE_ENABLED_STATUSES:raise NotFound()return view(*args, **kwargs)diff --git a/api/libs/email_i18n.py b/api/libs/email_i18n.pyindex 606dd9cfde0..fd4357cd539 100644--- a/api/libs/email_i18n.py+++ b/api/libs/email_i18n.py@@ -17,7 +17,7 @@ from pydantic import BaseModel, Fieldfrom extensions.ext_mail import mailfrom services.entities.feature_entities import BrandingModel-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServiceclass EmailType(StrEnum):@@ -136,7 +136,7 @@ class FeatureBrandingService:def get_branding_config(self) -> BrandingModel:"""Get branding configuration from feature service."""- return FeatureService.get_system_features().branding+ return SystemFeatureService.get_branding()class EmailSender(Protocol):diff --git a/api/libs/workspace_permission.py b/api/libs/workspace_permission.pyindex 969a81f5f9d..f6251a133af 100644--- a/api/libs/workspace_permission.py+++ b/api/libs/workspace_permission.py@@ -3,7 +3,7 @@ Workspace permission helper functions.These helpers check both billing/plan level and workspace-specific policy level permissions.Checks are performed at two levels:-1. Billing/plan level - via FeatureService (e.g., SANDBOX plan restrictions)+1. Billing/plan level - via an injected owner-transfer policy value2. Workspace policy level - via EnterpriseService (admin-configured per workspace)"""@@ -14,7 +14,6 @@ from werkzeug.exceptions import Forbiddenfrom configs import dify_configfrom enums import DeploymentEditionfrom services.enterprise.enterprise_service import EnterpriseService-from services.feature_service import FeatureServicelogger = logging.getLogger(__name__)@@ -45,7 +44,11 @@ def check_workspace_member_invite_permission(workspace_id: str) -> None:logger.exception("Failed to check workspace invite permission for %s", workspace_id)-def check_workspace_owner_transfer_permission(workspace_id: str) -> None:+def check_workspace_owner_transfer_permission(+ workspace_id: str,+ *,+ owner_transfer_allowed: bool,+) -> None:"""Check if workspace allows owner transfer at both billing and policy levels.@@ -55,12 +58,12 @@ def check_workspace_owner_transfer_permission(workspace_id: str) -> None:Args:workspace_id: The workspace ID to check permissions for+ owner_transfer_allowed: Whether the workspace plan permits ownership transferRaises:Forbidden: If either billing plan or workspace policy prohibits ownership transfer"""- features = FeatureService.get_features(workspace_id, exclude_vector_space=True)- if not features.is_allow_transfer_workspace:+ if not owner_transfer_allowed:raise Forbidden("Your current plan does not allow workspace ownership transfer")# Check the enterprise workspace policy only in the Enterprise edition.diff --git a/api/repositories/web_passport_repository.py b/api/repositories/web_passport_repository.pynew file mode 100644index 00000000000..f312c92d007--- /dev/null+++ b/api/repositories/web_passport_repository.py@@ -0,0 +1,150 @@+"""SQLAlchemy persistence adapter for web passport issuance."""++from collections.abc import Callable++from sqlalchemy import func, select+from sqlalchemy.orm import Session, sessionmaker++from models.enums import AppStatus, EndUserType+from models.model import App, EndUser, Site+from services.entities.passport_entities import EndUserRecord, WebAppRecord, WebPassportEndUserResolution+++class WebPassportRepository:+ def __init__(+ self,+ *,+ session_factory: sessionmaker[Session],+ generate_session_id: Callable[[], str],+ ) -> None:+ self._session_factory = session_factory+ self._generate_session_id = generate_session_id++ def get_active_web_app(self, app_code: str) -> WebAppRecord | None:+ stmt = self._active_web_app_stmt(app_code).limit(1)+ with self._session_factory() as session:+ row = session.execute(stmt).one_or_none()+ if row is None:+ return None+ site_id, app_id, tenant_id, persisted_app_code = row+ return WebAppRecord(+ site_id=str(site_id),+ app_id=str(app_id),+ tenant_id=str(tenant_id),+ app_code=str(persisted_app_code),+ )++ def is_web_app_active(self, app: WebAppRecord) -> bool:+ with self._session_factory() as session:+ return self._is_web_app_active(session, app)++ def resolve_standard_end_user(+ self,+ app: WebAppRecord,+ session_id: str | None,+ ) -> WebPassportEndUserResolution:+ with self._session_factory.begin() as session:+ if not self._is_web_app_active(session, app):+ return WebPassportEndUserResolution(app_active=False, end_user=None)++ if session_id:+ end_user = self._find_end_user_by_session_id(session, app, session_id)+ if end_user is not None:+ return WebPassportEndUserResolution(app_active=True, end_user=end_user)+ else:+ session_id = self._generate_unique_session_id(session)++ end_user = self._create_anonymous_end_user(session, app, session_id)+ return WebPassportEndUserResolution(app_active=True, end_user=end_user)++ def resolve_authenticated_end_user(+ self,+ app: WebAppRecord,+ *,+ end_user_id: str | None,+ session_id: str | None,+ ) -> WebPassportEndUserResolution:+ with self._session_factory.begin() as session:+ if not self._is_web_app_active(session, app):+ return WebPassportEndUserResolution(app_active=False, end_user=None)++ end_user = None+ if session_id:+ end_user = self._find_end_user_by_session_id(session, app, session_id)+ if end_user is None:+ end_user = self._create_anonymous_end_user(session, app, session_id)+ elif end_user_id:+ end_user = self._find_end_user_by_id(session, app, end_user_id)++ return WebPassportEndUserResolution(app_active=True, end_user=end_user)++ @staticmethod+ def _active_web_app_stmt(app_code: str):+ return (+ select(Site.id, App.id, App.tenant_id, Site.code)+ .join(App, App.id == Site.app_id)+ .where(+ Site.code == app_code,+ Site.status == AppStatus.NORMAL,+ App.status == AppStatus.NORMAL,+ App.enable_site.is_(True),+ )+ )++ def _is_web_app_active(self, session: Session, app: WebAppRecord) -> bool:+ stmt = self._active_web_app_stmt(app.app_code).where(+ Site.id == app.site_id,+ App.id == app.app_id,+ App.tenant_id == app.tenant_id,+ )+ return session.execute(stmt.limit(1)).one_or_none() is not None++ @staticmethod+ def _find_end_user_by_id(session: Session, app: WebAppRecord, end_user_id: str) -> EndUserRecord | None:+ persisted_id = session.scalar(+ select(EndUser.id).where(+ EndUser.id == end_user_id,+ EndUser.tenant_id == app.tenant_id,+ EndUser.app_id == app.app_id,+ )+ )+ return EndUserRecord(id=persisted_id) if persisted_id is not None else None++ @staticmethod+ def _find_end_user_by_session_id(+ session: Session,+ app: WebAppRecord,+ session_id: str,+ ) -> EndUserRecord | None:+ end_user_id = session.scalar(+ select(EndUser.id).where(+ EndUser.session_id == session_id,+ EndUser.tenant_id == app.tenant_id,+ EndUser.app_id == app.app_id,+ )+ )+ return EndUserRecord(id=end_user_id) if end_user_id is not None else None++ @staticmethod+ def _create_anonymous_end_user(+ session: Session,+ app: WebAppRecord,+ session_id: str,+ ) -> EndUserRecord:+ end_user = EndUser(+ tenant_id=app.tenant_id,+ app_id=app.app_id,+ type=EndUserType.BROWSER,+ is_anonymous=True,+ session_id=session_id,+ )+ session.add(end_user)+ session.flush()+ return EndUserRecord(id=end_user.id)++ def _generate_unique_session_id(self, session: Session) -> str:+ while True:+ session_id = self._generate_session_id()+ stmt = select(func.count()).select_from(EndUser).where(EndUser.session_id == session_id)+ if not session.scalar(stmt):+ return session_iddiff --git a/api/services/account_service.py b/api/services/account_service.pyindex b022187e14d..6e5fda0b0ba 100644--- a/api/services/account_service.py+++ b/api/services/account_service.py@@ -79,8 +79,8 @@ from services.errors.account import (SeatsLimitExceededError,)from services.errors.workspace import WorkSpaceNotAllowedCreateError, WorkspacesLimitExceededError-from services.feature_service import FeatureServicefrom services.plugin.plugin_auto_upgrade_service import PluginAutoUpgradeService+from services.system_feature_service import SystemFeatureServicefrom services.telemetry_service import CommunityTelemetryServicefrom tasks.mail_change_mail_task import (send_change_mail_completed_notification_task,@@ -446,7 +446,7 @@ class AccountService:session: Session,) -> Account:"""Create an account, preferring explicit user timezone over language-derived defaults."""- if not FeatureService.get_system_features().is_allow_register and not is_setup:+ if not SystemFeatureService.is_registration_allowed() and not is_setup:from controllers.console.error import AccountNotFoundraise AccountNotFound()@@ -458,7 +458,7 @@ class AccountService:# 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 FeatureService.get_license().seats.is_available():+ 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):@@ -1139,7 +1139,7 @@ class TenantService:session: Session,) -> Tenant:"""Create tenant"""- if not FeatureService.is_workspace_creation_allowed() and not is_setup and not is_from_dashboard:+ if not SystemFeatureService.is_workspace_creation_allowed() and not is_setup and not is_from_dashboard:from controllers.console.error import NotAllowedCreateWorkspaceraise NotAllowedCreateWorkspace()@@ -1202,10 +1202,10 @@ class TenantService:owner. It persists the legacy membership before creating the matchingRBAC role binding, then makes the workspace current for the account."""- if not FeatureService.is_workspace_creation_allowed() and not is_setup and not is_from_dashboard:+ if not SystemFeatureService.is_workspace_creation_allowed() and not is_setup and not is_from_dashboard:raise WorkSpaceNotAllowedCreateError()- workspaces = FeatureService.get_license().workspaces+ workspaces = SystemFeatureService.get_license().workspacesif not workspaces.is_available():raise WorkspacesLimitExceededError()@@ -1938,9 +1938,9 @@ class RegisterService:AccountService.link_account_integrate(provider, open_id, account, session=session)if (- FeatureService.is_workspace_creation_allowed()+ SystemFeatureService.is_workspace_creation_allowed()and create_workspace_required- and FeatureService.get_license().workspaces.is_available()+ and SystemFeatureService.get_license().workspaces.is_available()):try:TenantService.create_owner_tenant(account, session=session)diff --git a/api/services/agent/roster_service.py b/api/services/agent/roster_service.pyindex ccb79c65dca..a45ab42bf28 100644--- a/api/services/agent/roster_service.py+++ b/api/services/agent/roster_service.py@@ -44,7 +44,7 @@ from services.agent.workspace_service import AgentWorkspaceNotFoundError, AgentWfrom services.app_service import AppService, CreateAppParamsfrom services.enterprise.enterprise_service import EnterpriseServicefrom services.entities.agent_entities import RosterAgentCreatePayload, RosterAgentUpdatePayload-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServicefrom tasks.collect_agent_resources_task import enqueue_agent_resource_collectionlogger = logging.getLogger(__name__)@@ -1120,7 +1120,7 @@ class AgentRosterService:source_include_draft=not source_agent.active_config_is_published,)self._session.commit()- if FeatureService.get_system_features().webapp_auth.enabled:+ if SystemFeatureService.is_webapp_auth_enabled():try:original_settings = EnterpriseService.WebAppAuth.get_app_access_mode_by_id(source_app.id)access_mode = original_settings.access_modediff --git a/api/services/app_service.py b/api/services/app_service.pyindex 89b622463b7..30797c97ede 100644--- a/api/services/app_service.py+++ b/api/services/app_service.py@@ -49,8 +49,8 @@ from services.agent.workspace_service import AgentWorkspaceServicefrom services.billing_service import BillingServicefrom services.enterprise import rbac_service as enterprise_rbac_servicefrom services.enterprise.enterprise_service import EnterpriseService-from services.feature_service import FeatureServicefrom services.openapi.visibility import apply_openapi_gate, is_openapi_visible+from services.system_feature_service import SystemFeatureServicefrom services.tag_service import TagServicefrom tasks.collect_agent_resources_task import enqueue_agent_resource_collectionfrom tasks.remove_app_and_related_data_task import remove_app_and_related_data_task@@ -703,7 +703,7 @@ class AppService:app.id,)- if FeatureService.get_system_features().webapp_auth.enabled:+ if SystemFeatureService.is_webapp_auth_enabled():# update web app setting as privateEnterpriseService.WebAppAuth.update_app_access_mode(app.id, "private")@@ -1155,7 +1155,7 @@ class AppService:)# clean up web app settings- if FeatureService.get_system_features().webapp_auth.enabled:+ if SystemFeatureService.is_webapp_auth_enabled():EnterpriseService.WebAppAuth.cleanup_webapp(app.id)if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:diff --git a/api/services/entities/mail_entities.py b/api/services/entities/mail_entities.pynew file mode 100644index 00000000000..221cb00a812--- /dev/null+++ b/api/services/entities/mail_entities.py@@ -0,0 +1,12 @@+"""Framework-neutral data contracts for internal mail delivery."""++from dataclasses import dataclass+from typing import Any+++@dataclass(frozen=True, slots=True)+class InnerMailMessage:+ recipients: tuple[str, ...]+ subject: str+ body: str+ substitutions: dict[str, Any] | None = Nonediff --git a/api/services/entities/passport_entities.py b/api/services/entities/passport_entities.pynew file mode 100644index 00000000000..47186464f0c--- /dev/null+++ b/api/services/entities/passport_entities.py@@ -0,0 +1,47 @@+"""Framework-neutral data contracts for web passport issuance."""++from dataclasses import dataclass++from pydantic import BaseModel, ConfigDict+++@dataclass(frozen=True, slots=True)+class WebAppRecord:+ site_id: str+ app_id: str+ tenant_id: str+ app_code: str+++@dataclass(frozen=True, slots=True)+class EndUserRecord:+ id: str+++@dataclass(frozen=True, slots=True)+class WebPassportEndUserResolution:+ app_active: bool+ end_user: EndUserRecord | None+++@dataclass(frozen=True, slots=True)+class WebPassportRequest:+ app_code: str+ user_session_id: str | None+ access_token: str | None+++@dataclass(frozen=True, slots=True)+class WebPassportResult:+ access_token: str+++class WebAppLoginClaims(BaseModel):+ token_source: str | None = None+ user_id: str | None = None+ end_user_id: str | None = None+ session_id: str | None = None+ auth_type: str | None = None+ exp: int | None = None++ model_config = ConfigDict(extra="ignore")diff --git a/api/services/feature_query_service.py b/api/services/feature_query_service.pyindex 8e0c82e6e25..b3a72ab9ea8 100644--- a/api/services/feature_query_service.py+++ b/api/services/feature_query_service.py@@ -36,10 +36,16 @@ class FeatureQueryService:self._app_dsl_version = app_dsl_versiondef get_features(self, context: RequestContext) -> FeatureModel:- return self._features.get_workspace_features(self._require_active_workspace(context))+ return self.get_workspace_features(self._require_active_workspace(context))++ def get_workspace_features(self, workspace_id: str) -> FeatureModel:+ return self._features.get_workspace_features(workspace_id)def get_vector_space(self, context: RequestContext) -> VectorSpaceLimitationModel:- return self._features.get_vector_space(self._require_active_workspace(context))+ return self.get_workspace_vector_space(self._require_active_workspace(context))++ def get_workspace_vector_space(self, workspace_id: str) -> VectorSpaceLimitationModel:+ return self._features.get_vector_space(workspace_id)def get_trial_models(self, context: RequestContext) -> list[str]:return self._features.get_trial_models(self._require_active_workspace(context))@@ -47,7 +53,7 @@ class FeatureQueryService:def get_app_dsl_version(self) -> str:return self._app_dsl_version- def get_system_features(self) -> SystemFeatureModel:+ def get_public_system_features(self) -> SystemFeatureModel:return self._features.get_public_system_features()def get_license(self) -> LicenseModel:diff --git a/api/services/feature_service.py b/api/services/feature_service.pyindex 579316e8fe8..b7627e9df4a 100644--- a/api/services/feature_service.py+++ b/api/services/feature_service.py@@ -1,23 +1,9 @@-import logging-from collections.abc import Mapping--from pydantic import BaseModel, ConfigDict, Field, ValidationError-from configs import dify_configfrom enums import CloudPlan, DeploymentEdition, HostedTrialProviderfrom services.billing_service import BillingInfo, BillingServicefrom services.enterprise.enterprise_service import EnterpriseServicefrom services.entities import feature_entities-logger = logging.getLogger(__name__)---class _EnterprisePluginInstallationPermission(BaseModel):- model_config = ConfigDict(extra="ignore")-- plugin_installation_scope: feature_entities.PluginInstallationScope = Field(alias="pluginInstallationScope")- restrict_to_marketplace_only: bool = Field(alias="restrictToMarketplaceOnly", strict=True)-class FeatureService:@classmethod@@ -102,90 +88,6 @@ class FeatureService:return Falsereturn features.billing.enabled and features.billing.subscription.plan.is_paid- @classmethod- def get_system_features(cls) -> feature_entities.SystemFeatureModel:- system_features = feature_entities.SystemFeatureModel(deployment_edition=dify_config.DEPLOYMENT_EDITION)- system_features.rbac_enabled = dify_config.RBAC_ENABLED-- cls._fulfill_system_params_from_env(system_features)- system_features.webapp_auth.enabled = cls.is_webapp_auth_enabled()-- if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.ENTERPRISE:- system_features.branding.enabled = True- system_features.enable_change_email = False- cls._fulfill_params_from_enterprise(system_features)-- if dify_config.MARKETPLACE_ENABLED:- system_features.enable_marketplace = True-- if dify_config.CREATORS_PLATFORM_FEATURES_ENABLED:- system_features.enable_creators_platform = True-- return system_features-- @classmethod- def is_workspace_creation_allowed(cls) -> bool:- """Resolve the backend workspace-creation policy, including the Enterprise override."""- is_allowed = dify_config.ALLOW_CREATE_WORKSPACE- if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.ENTERPRISE:- return is_allowed-- enterprise_info = EnterpriseService.get_info()- return bool(enterprise_info.get("IsAllowCreateWorkspace", is_allowed))-- @classmethod- def is_plugin_manager_enabled(cls) -> bool:- """Return whether Enterprise plugin credential policies must be enforced."""- return dify_config.DEPLOYMENT_EDITION == DeploymentEdition.ENTERPRISE-- @classmethod- def get_plugin_installation_permission(cls) -> feature_entities.PluginInstallationPermissionModel:- """Resolve the validated deployment-wide plugin installation policy."""- if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.ENTERPRISE:- return feature_entities.PluginInstallationPermissionModel()-- return cls._resolve_plugin_installation_permission(EnterpriseService.get_info())-- @classmethod- def get_license(cls) -> feature_entities.LicenseModel:- """Return full license detail. Enterprise-only; requires an authenticated caller.-- Non-enterprise deployments have no license, so an unconstrained default- (unlimited seats/workspaces) is returned.- """- if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.ENTERPRISE:- return feature_entities.LicenseModel()- license_model = cls._build_license(EnterpriseService.get_info())- license_model.license_expiry_notice_enabled = dify_config.ENABLE_LICENSE_EXPIRY_NOTICE- return license_model-- @staticmethod- def is_explore_banner_enabled() -> bool:- return dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD and dify_config.ENABLE_EXPLORE_BANNER-- @staticmethod- def is_webapp_auth_enabled() -> bool:- return dify_config.DEPLOYMENT_EDITION == DeploymentEdition.ENTERPRISE-- @staticmethod- def is_trial_app_enabled() -> bool:- return dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD and dify_config.ENABLE_TRIAL_APP-- @classmethod- def _fulfill_system_params_from_env(cls, system_features: feature_entities.SystemFeatureModel):- system_features.enable_email_code_login = dify_config.ENABLE_EMAIL_CODE_LOGIN- system_features.enable_email_password_login = dify_config.ENABLE_EMAIL_PASSWORD_LOGIN- system_features.enable_social_oauth_login = dify_config.ENABLE_SOCIAL_OAUTH_LOGIN- system_features.enable_collaboration_mode = dify_config.ENABLE_COLLABORATION_MODE- system_features.is_allow_register = dify_config.ALLOW_REGISTER- system_features.is_email_setup = dify_config.MAIL_TYPE is not None and dify_config.MAIL_TYPE != ""- system_features.enable_change_email = dify_config.ENABLE_CHANGE_EMAIL- system_features.enable_explore_banner = cls.is_explore_banner_enabled()- system_features.enable_learn_app = dify_config.ENABLE_LEARN_APP- system_features.webapp_auth.allow_public_access = dify_config.WEBAPP_PUBLIC_ACCESS_ENABLED- system_features.enable_step_by_step_tour = dify_config.ENABLE_STEP_BY_STEP_TOUR- system_features.knowledge_fs_enabled = dify_config.KNOWLEDGE_FS_ENABLED-@classmethoddef _fulfill_trial_models_from_env(cls, quota_types: tuple[str, ...] | None = None) -> list[str]:allowed_quota_types = quota_types or ("PAID", "TRIAL")@@ -311,125 +213,3 @@ class FeatureService:# but feature API keeps LimitationModel.size as int for compatibility.vector_space.size = int(billing_info["vector_space"]["size"])vector_space.limit = billing_info["vector_space"]["limit"]-- @classmethod- def _build_license(cls, enterprise_info: dict) -> feature_entities.LicenseModel:- license_model = feature_entities.LicenseModel()- if license_info := enterprise_info.get("License"):- license_model.status = feature_entities.LicenseStatus(- license_info.get("status", feature_entities.LicenseStatus.INACTIVE)- )- license_model.expired_at = license_info.get("expiredAt", "")- if workspaces_info := license_info.get("workspaces"):- license_model.workspaces = feature_entities.LicenseLimitationModel(- enabled=workspaces_info.get("enabled", False),- limit=workspaces_info.get("limit", 0),- size=workspaces_info.get("used", 0),- )- if seats_info := license_info.get("licensedSeats"):- license_model.seats = feature_entities.LicenseLimitationModel(- enabled=seats_info.get("enabled", False),- limit=seats_info.get("limit", 0),- size=seats_info.get("used", 0),- )- return license_model-- @classmethod- def _resolve_plugin_installation_permission(- cls, enterprise_info: Mapping[str, object]- ) -> feature_entities.PluginInstallationPermissionModel:- if "PluginInstallationPermission" not in enterprise_info:- return feature_entities.PluginInstallationPermissionModel()-- try:- permission = _EnterprisePluginInstallationPermission.model_validate(- enterprise_info["PluginInstallationPermission"]- )- except ValidationError as exc:- # Do not attach the exception because it may contain raw Enterprise configuration values.- logger.error( # noqa: TRY400- "Invalid Enterprise plugin installation permission; denying all plugin installations: %s",- exc.errors(include_input=False),- )- return feature_entities.PluginInstallationPermissionModel(- plugin_installation_scope=feature_entities.PluginInstallationScope.NONE,- restrict_to_marketplace_only=True,- )-- return feature_entities.PluginInstallationPermissionModel(- plugin_installation_scope=permission.plugin_installation_scope,- restrict_to_marketplace_only=permission.restrict_to_marketplace_only,- )-- @staticmethod- def _resolve_sso_protocol(value: object, *, field_name: str) -> feature_entities.SSOProtocol | None:- if value is None or (isinstance(value, str) and not value.strip()):- return None-- if not isinstance(value, str):- logger.error("Invalid Enterprise SSO protocol for %s; disabling the protocol", field_name)- return None-- try:- return feature_entities.SSOProtocol(value)- except ValueError:- logger.error( # noqa: TRY400- "Invalid Enterprise SSO protocol for %s; disabling the protocol", field_name- )- return None-- @classmethod- def _fulfill_params_from_enterprise(cls, features: feature_entities.SystemFeatureModel):- enterprise_info = EnterpriseService.get_info()-- if "SSOEnforcedForSignin" in enterprise_info:- features.sso_enforced_for_signin = enterprise_info["SSOEnforcedForSignin"]-- features.sso_enforced_for_signin_protocol = cls._resolve_sso_protocol(- enterprise_info.get("SSOEnforcedForSigninProtocol"),- field_name="SSOEnforcedForSigninProtocol",- )-- if "EnableEmailCodeLogin" in enterprise_info:- features.enable_email_code_login = enterprise_info["EnableEmailCodeLogin"]-- if "EnableEmailPasswordLogin" in enterprise_info:- features.enable_email_password_login = enterprise_info["EnableEmailPasswordLogin"]-- if "IsAllowRegister" in enterprise_info:- features.is_allow_register = enterprise_info["IsAllowRegister"]-- if "EnableAppDeploy" in enterprise_info:- features.enable_app_deploy = enterprise_info["EnableAppDeploy"]-- if "Branding" in enterprise_info:- features.branding.application_title = enterprise_info["Branding"].get("applicationTitle", "")- features.branding.login_page_logo = enterprise_info["Branding"].get("loginPageLogo", "")- features.branding.workspace_logo = enterprise_info["Branding"].get("workspaceLogo", "")- features.branding.favicon = enterprise_info["Branding"].get("favicon", "")-- if "WebAppAuth" in enterprise_info:- features.webapp_auth.allow_sso = enterprise_info["WebAppAuth"].get("allowSso", False)- features.webapp_auth.allow_email_code_login = enterprise_info["WebAppAuth"].get(- "allowEmailCodeLogin", False- )- features.webapp_auth.allow_email_password_login = enterprise_info["WebAppAuth"].get(- "allowEmailPasswordLogin", False- )- features.webapp_auth.sso_config.protocol = cls._resolve_sso_protocol(- enterprise_info.get("SSOEnforcedForWebProtocol"),- field_name="SSOEnforcedForWebProtocol",- )-- # SECURITY NOTE: system-features is unauthenticated, so it exposes only license- # *status* — enough for the login page to detect an expired/inactive license after- # force-logout. Full license detail (expiry, workspace/seat usage) is served- # separately by get_license() behind an authenticated endpoint.- if license_info := enterprise_info.get("License"):- features.license = feature_entities.LicenseStatusModel(- status=feature_entities.LicenseStatus(- license_info.get("status", feature_entities.LicenseStatus.INACTIVE)- )- )-- features.plugin_installation_permission = cls._resolve_plugin_installation_permission(enterprise_info)diff --git a/api/services/feature_service_gateway.py b/api/services/feature_service_gateway.pyindex 1a93b380dd5..4ecd9593817 100644--- a/api/services/feature_service_gateway.py+++ b/api/services/feature_service_gateway.py@@ -1,4 +1,4 @@-"""Feature-query gateway backed by the existing FeatureService."""+"""Feature-query gateway combining workspace and deployment feature providers."""from typing import override@@ -10,10 +10,11 @@ from services.entities.feature_entities import ()from services.feature_query_service import FeatureQueryGatewayfrom services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServiceclass FeatureServiceGateway(FeatureQueryGateway):- """Read dynamic feature resources through FeatureService."""+ """Read workspace features from FeatureService and deployment features from SystemFeatureService."""@overridedef get_workspace_features(self, workspace_id: str) -> FeatureModel:@@ -29,8 +30,8 @@ class FeatureServiceGateway(FeatureQueryGateway):@overridedef get_public_system_features(self) -> SystemFeatureModel:- return FeatureService.get_system_features()+ return SystemFeatureService.get_public_system_features()@overridedef get_license(self) -> LicenseModel:- return FeatureService.get_license()+ return SystemFeatureService.get_license()diff --git a/api/services/inner_mail_service.py b/api/services/inner_mail_service.pynew file mode 100644index 00000000000..a59236daeb8--- /dev/null+++ b/api/services/inner_mail_service.py@@ -0,0 +1,17 @@+"""Application service for mail received through the inner API."""++from typing import Protocol++from services.entities.mail_entities import InnerMailMessage+++class InnerMailDispatcher(Protocol):+ def __call__(self, message: InnerMailMessage) -> None: ...+++class InnerMailService:+ def __init__(self, *, dispatch: InnerMailDispatcher) -> None:+ self._dispatch = dispatch++ def send(self, message: InnerMailMessage) -> None:+ self._dispatch(message)diff --git a/api/services/installed_app_service.py b/api/services/installed_app_service.pyindex e3ff637190e..ba879e4bfbf 100644--- a/api/services/installed_app_service.py+++ b/api/services/installed_app_service.py@@ -8,7 +8,7 @@ from libs.helper import escape_like_patternfrom models import App, AppModelConfig, InstalledApp, Workflowfrom models.model import AppModefrom services.enterprise.enterprise_service import EnterpriseService-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServiceclass InstalledAppCursor(BaseModel):@@ -118,7 +118,7 @@ class InstalledAppService:escaped_name = escape_like_pattern(normalized_name)stmt = stmt.where(App.name.ilike(f"%{escaped_name}%", escape="\\"))- webapp_auth_enabled = FeatureService.get_system_features().webapp_auth.enabled+ webapp_auth_enabled = SystemFeatureService.is_webapp_auth_enabled()scan_size = limit * 2 if webapp_auth_enabled else limit + 1visible_rows: list[tuple[InstalledApp, App]] = []scan_cursor = cursordiff --git a/api/services/openapi/license_gate.py b/api/services/openapi/license_gate.pyindex 7ca7779de6f..8df92eb344b 100644--- a/api/services/openapi/license_gate.py+++ b/api/services/openapi/license_gate.py@@ -5,8 +5,7 @@ the EE blueprint chain is what gives CE deploys no callers on this surfacein practice, but the explicit short-circuit avoids any test/fixture thatflips the surface on without flipping the license.-Reuses ``FeatureService.get_system_features()`` so the license status-travels the same path as the console reads.+Uses the narrow system license policy shared with Console admission.Companion to ``controllers.console.wraps.enterprise_license_required`` —that one is for console (cookie-authed, force-logout 401). This one is@@ -24,7 +23,7 @@ from werkzeug.exceptions import Forbiddenfrom configs import dify_configfrom enums import DeploymentEditionfrom services.entities.feature_entities import LicenseStatus-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServicelogger = logging.getLogger(__name__)@@ -47,8 +46,8 @@ def license_required[**P, R](view: Callable[P, R]) -> Callable[P, R]:def _is_license_valid() -> bool:try:- features = FeatureService.get_system_features()+ license_status = SystemFeatureService.get_license_status()except Exception:- logger.exception("license_gate: FeatureService.get_system_features failed")+ logger.exception("license_gate: SystemFeatureService.get_license_status failed")return False- return features.license.status in _VALID_LICENSE_STATUSES+ return license_status in _VALID_LICENSE_STATUSESdiff --git a/api/services/system_feature_service.py b/api/services/system_feature_service.pynew file mode 100644index 00000000000..b459e8ec56f--- /dev/null+++ b/api/services/system_feature_service.py@@ -0,0 +1,287 @@+"""Deployment-wide feature policies and the public system-features snapshot."""++import logging+from collections.abc import Mapping++from pydantic import BaseModel, ConfigDict, Field, ValidationError++from configs import dify_config+from enums import DeploymentEdition+from services.enterprise.enterprise_service import EnterpriseService+from services.entities import feature_entities++logger = logging.getLogger(__name__)+++class _EnterprisePluginInstallationPermission(BaseModel):+ model_config = ConfigDict(extra="ignore")++ plugin_installation_scope: feature_entities.PluginInstallationScope = Field(alias="pluginInstallationScope")+ restrict_to_marketplace_only: bool = Field(alias="restrictToMarketplaceOnly", strict=True)+++class SystemFeatureService:+ """Resolve deployment-wide policies without exposing the public response DTO internally."""++ @classmethod+ def get_public_system_features(cls) -> feature_entities.SystemFeatureModel:+ """Build the non-sensitive bootstrap snapshot shared by Console and Web."""+ system_features = feature_entities.SystemFeatureModel(deployment_edition=dify_config.DEPLOYMENT_EDITION)+ system_features.rbac_enabled = dify_config.RBAC_ENABLED++ cls._fulfill_system_params_from_env(system_features)++ if cls.is_webapp_auth_enabled():+ system_features.branding.enabled = True+ system_features.webapp_auth.enabled = True+ system_features.enable_change_email = False+ cls._fulfill_params_from_enterprise(system_features)++ if dify_config.MARKETPLACE_ENABLED:+ system_features.enable_marketplace = True++ if dify_config.CREATORS_PLATFORM_FEATURES_ENABLED:+ system_features.enable_creators_platform = True++ return system_features++ @classmethod+ def is_registration_allowed(cls) -> bool:+ """Return the effective registration policy, including the Enterprise override."""+ is_allowed = dify_config.ALLOW_REGISTER+ if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.ENTERPRISE:+ return is_allowed++ enterprise_info = EnterpriseService.get_info()+ return bool(enterprise_info.get("IsAllowRegister", is_allowed))++ @classmethod+ def is_email_password_login_enabled(cls) -> bool:+ """Return the effective password-login policy, including the Enterprise override."""+ is_enabled = dify_config.ENABLE_EMAIL_PASSWORD_LOGIN+ if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.ENTERPRISE:+ return is_enabled++ enterprise_info = EnterpriseService.get_info()+ return bool(enterprise_info.get("EnableEmailPasswordLogin", is_enabled))++ @staticmethod+ def is_change_email_enabled() -> bool:+ """Return whether Console accounts may change their email address."""+ if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.ENTERPRISE:+ return False+ return dify_config.ENABLE_CHANGE_EMAIL++ @staticmethod+ def is_webapp_auth_enabled(*, deployment_edition: DeploymentEdition | None = None) -> bool:+ """Return whether deployment-level WebApp authentication integration is enabled."""+ edition = deployment_edition if deployment_edition is not None else dify_config.DEPLOYMENT_EDITION+ return edition == DeploymentEdition.ENTERPRISE++ @classmethod+ def get_license_status(cls) -> feature_entities.LicenseStatus:+ """Return the deployment license status used by internal admission policies."""+ if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.ENTERPRISE:+ return feature_entities.LicenseStatus.NONE+ return cls._resolve_license_status(EnterpriseService.get_info())++ @classmethod+ def get_branding(cls) -> feature_entities.BrandingModel:+ """Return the deployment branding used by server-rendered email."""+ branding = feature_entities.BrandingModel(enabled=cls.is_webapp_auth_enabled())+ if not branding.enabled:+ return branding++ enterprise_info = EnterpriseService.get_info()+ if branding_info := enterprise_info.get("Branding"):+ branding.application_title = branding_info.get("applicationTitle", "")+ branding.login_page_logo = branding_info.get("loginPageLogo", "")+ branding.workspace_logo = branding_info.get("workspaceLogo", "")+ branding.favicon = branding_info.get("favicon", "")+ return branding++ @classmethod+ def is_workspace_creation_allowed(cls) -> bool:+ """Resolve the backend workspace-creation policy, including the Enterprise override."""+ is_allowed = dify_config.ALLOW_CREATE_WORKSPACE+ if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.ENTERPRISE:+ return is_allowed++ enterprise_info = EnterpriseService.get_info()+ return bool(enterprise_info.get("IsAllowCreateWorkspace", is_allowed))++ @staticmethod+ def is_plugin_manager_enabled() -> bool:+ """Return whether Enterprise plugin credential policies must be enforced."""+ return dify_config.DEPLOYMENT_EDITION == DeploymentEdition.ENTERPRISE++ @classmethod+ def get_plugin_installation_permission(cls) -> feature_entities.PluginInstallationPermissionModel:+ """Resolve the validated deployment-wide plugin installation policy."""+ if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.ENTERPRISE:+ return feature_entities.PluginInstallationPermissionModel()++ return cls._resolve_plugin_installation_permission(EnterpriseService.get_info())++ @classmethod+ def get_license(cls) -> feature_entities.LicenseModel:+ """Return full license detail for authenticated server-side consumers."""+ if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.ENTERPRISE:+ return feature_entities.LicenseModel()+ license_model = cls._build_license(EnterpriseService.get_info())+ license_model.license_expiry_notice_enabled = dify_config.ENABLE_LICENSE_EXPIRY_NOTICE+ return license_model++ @staticmethod+ def is_explore_banner_enabled() -> bool:+ return dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD and dify_config.ENABLE_EXPLORE_BANNER++ @staticmethod+ def is_trial_app_enabled() -> bool:+ return dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD and dify_config.ENABLE_TRIAL_APP++ @classmethod+ def _fulfill_system_params_from_env(cls, system_features: feature_entities.SystemFeatureModel) -> None:+ system_features.enable_email_code_login = dify_config.ENABLE_EMAIL_CODE_LOGIN+ system_features.enable_email_password_login = dify_config.ENABLE_EMAIL_PASSWORD_LOGIN+ system_features.enable_social_oauth_login = dify_config.ENABLE_SOCIAL_OAUTH_LOGIN+ system_features.enable_collaboration_mode = dify_config.ENABLE_COLLABORATION_MODE+ system_features.is_allow_register = dify_config.ALLOW_REGISTER+ system_features.is_email_setup = dify_config.MAIL_TYPE is not None and dify_config.MAIL_TYPE != ""+ system_features.enable_change_email = dify_config.ENABLE_CHANGE_EMAIL+ system_features.enable_explore_banner = cls.is_explore_banner_enabled()+ system_features.enable_learn_app = dify_config.ENABLE_LEARN_APP+ system_features.webapp_auth.allow_public_access = dify_config.WEBAPP_PUBLIC_ACCESS_ENABLED+ system_features.enable_step_by_step_tour = dify_config.ENABLE_STEP_BY_STEP_TOUR+ system_features.knowledge_fs_enabled = dify_config.KNOWLEDGE_FS_ENABLED++ @classmethod+ def _fulfill_params_from_enterprise(cls, features: feature_entities.SystemFeatureModel) -> None:+ enterprise_info = EnterpriseService.get_info()++ if "SSOEnforcedForSignin" in enterprise_info:+ features.sso_enforced_for_signin = enterprise_info["SSOEnforcedForSignin"]++ features.sso_enforced_for_signin_protocol = cls._resolve_sso_protocol(+ enterprise_info.get("SSOEnforcedForSigninProtocol"),+ field_name="SSOEnforcedForSigninProtocol",+ )++ if "EnableEmailCodeLogin" in enterprise_info:+ features.enable_email_code_login = enterprise_info["EnableEmailCodeLogin"]++ if "EnableEmailPasswordLogin" in enterprise_info:+ features.enable_email_password_login = enterprise_info["EnableEmailPasswordLogin"]++ if "IsAllowRegister" in enterprise_info:+ features.is_allow_register = enterprise_info["IsAllowRegister"]++ if "EnableAppDeploy" in enterprise_info:+ features.enable_app_deploy = enterprise_info["EnableAppDeploy"]++ if "Branding" in enterprise_info:+ features.branding.application_title = enterprise_info["Branding"].get("applicationTitle", "")+ features.branding.login_page_logo = enterprise_info["Branding"].get("loginPageLogo", "")+ features.branding.workspace_logo = enterprise_info["Branding"].get("workspaceLogo", "")+ features.branding.favicon = enterprise_info["Branding"].get("favicon", "")++ if "WebAppAuth" in enterprise_info:+ features.webapp_auth.allow_sso = enterprise_info["WebAppAuth"].get("allowSso", False)+ features.webapp_auth.allow_email_code_login = enterprise_info["WebAppAuth"].get(+ "allowEmailCodeLogin", False+ )+ features.webapp_auth.allow_email_password_login = enterprise_info["WebAppAuth"].get(+ "allowEmailPasswordLogin", False+ )+ features.webapp_auth.sso_config.protocol = cls._resolve_sso_protocol(+ enterprise_info.get("SSOEnforcedForWebProtocol"),+ field_name="SSOEnforcedForWebProtocol",+ )++ # The unauthenticated endpoint exposes status only. Full license detail is+ # served by the authenticated license endpoint.+ license_status = cls._resolve_license_status(enterprise_info)+ if license_status != feature_entities.LicenseStatus.NONE:+ features.license = feature_entities.LicenseStatusModel(+ status=license_status,+ )++ features.plugin_installation_permission = cls._resolve_plugin_installation_permission(enterprise_info)++ @staticmethod+ def _resolve_license_status(enterprise_info: Mapping[str, object]) -> feature_entities.LicenseStatus:+ license_info = enterprise_info.get("License")+ if not license_info:+ return feature_entities.LicenseStatus.NONE+ if not isinstance(license_info, Mapping):+ return feature_entities.LicenseStatus.INACTIVE++ status = license_info.get("status", feature_entities.LicenseStatus.INACTIVE)+ if isinstance(status, feature_entities.LicenseStatus):+ return status+ if isinstance(status, str):+ return feature_entities.LicenseStatus(status)+ return feature_entities.LicenseStatus.INACTIVE++ @classmethod+ def _build_license(cls, enterprise_info: dict) -> feature_entities.LicenseModel:+ license_model = feature_entities.LicenseModel()+ if license_info := enterprise_info.get("License"):+ license_model.status = feature_entities.LicenseStatus(+ license_info.get("status", feature_entities.LicenseStatus.INACTIVE)+ )+ license_model.expired_at = license_info.get("expiredAt", "")+ if workspaces_info := license_info.get("workspaces"):+ license_model.workspaces = feature_entities.LicenseLimitationModel(+ enabled=workspaces_info.get("enabled", False),+ limit=workspaces_info.get("limit", 0),+ size=workspaces_info.get("used", 0),+ )+ if seats_info := license_info.get("licensedSeats"):+ license_model.seats = feature_entities.LicenseLimitationModel(+ enabled=seats_info.get("enabled", False),+ limit=seats_info.get("limit", 0),+ size=seats_info.get("used", 0),+ )+ return license_model++ @classmethod+ def _resolve_plugin_installation_permission(+ cls, enterprise_info: Mapping[str, object]+ ) -> feature_entities.PluginInstallationPermissionModel:+ if "PluginInstallationPermission" not in enterprise_info:+ return feature_entities.PluginInstallationPermissionModel()++ try:+ permission = _EnterprisePluginInstallationPermission.model_validate(+ enterprise_info["PluginInstallationPermission"]+ )+ except ValidationError as exc:+ logger.error( # noqa: TRY400+ "Invalid Enterprise plugin installation permission; denying all plugin installations: %s",+ exc.errors(include_input=False),+ )+ return feature_entities.PluginInstallationPermissionModel(+ plugin_installation_scope=feature_entities.PluginInstallationScope.NONE,+ restrict_to_marketplace_only=True,+ )++ return feature_entities.PluginInstallationPermissionModel(+ plugin_installation_scope=permission.plugin_installation_scope,+ restrict_to_marketplace_only=permission.restrict_to_marketplace_only,+ )++ @staticmethod+ def _resolve_sso_protocol(value: object, *, field_name: str) -> feature_entities.SSOProtocol | None:+ if value is None or (isinstance(value, str) and not value.strip()):+ return None++ if not isinstance(value, str):+ logger.error("Invalid Enterprise SSO protocol for %s; disabling the protocol", field_name)+ return None++ try:+ return feature_entities.SSOProtocol(value)+ except ValueError:+ logger.error("Invalid Enterprise SSO protocol for %s; disabling the protocol", field_name) # noqa: TRY400+ return Nonediff --git a/api/services/web_passport_gateways.py b/api/services/web_passport_gateways.pynew file mode 100644index 00000000000..f6cf423302a--- /dev/null+++ b/api/services/web_passport_gateways.py@@ -0,0 +1,49 @@+"""Outer gateways used by the web passport application service."""++from collections.abc import Callable, Mapping+from typing import Any++from werkzeug.exceptions import Unauthorized++from libs.passport import PassportService+from services.enterprise.enterprise_service import PERMISSION_CHECK_MODES, WebAppAccessMode, WebAppSettings+from services.web_passport_service import WebAppAuthType, WebPassportUnauthorizedError+++class DeploymentWebPassportAuthGateway:+ def __init__(+ self,+ *,+ webapp_auth_enabled: bool,+ get_app_access_mode: Callable[[str], WebAppSettings],+ ) -> None:+ self._webapp_auth_enabled = webapp_auth_enabled+ self._get_app_access_mode = get_app_access_mode++ def is_webapp_auth_enabled(self) -> bool:+ return self._webapp_auth_enabled++ def get_app_auth_type(self, app_id: str) -> WebAppAuthType:+ access_mode = self._get_app_access_mode(app_id).access_mode+ if access_mode == WebAppAccessMode.PUBLIC:+ return WebAppAuthType.PUBLIC+ if access_mode in PERMISSION_CHECK_MODES:+ return WebAppAuthType.INTERNAL+ if access_mode == WebAppAccessMode.SSO_VERIFIED:+ return WebAppAuthType.EXTERNAL+ raise ValueError(f"Unsupported web app access mode: {access_mode}")+++class PassportTokenGateway:+ def __init__(self, *, passport: PassportService) -> None:+ self._passport = passport++ def verify(self, token: str) -> Mapping[str, Any]:+ try:+ return self._passport.verify(token)+ except Unauthorized as exc:+ description = exc.description or "Invalid token."+ raise WebPassportUnauthorizedError(description) from exc++ def issue(self, payload: Mapping[str, Any]) -> str:+ return self._passport.issue(dict(payload))diff --git a/api/services/web_passport_service.py b/api/services/web_passport_service.pynew file mode 100644index 00000000000..65240368ce6--- /dev/null+++ b/api/services/web_passport_service.py@@ -0,0 +1,185 @@+"""Application service for issuing passports used by deployed web applications."""++from collections.abc import Callable, Mapping+from datetime import datetime, timedelta+from enum import StrEnum+from typing import Any, Protocol++from pydantic import ValidationError++from services.entities.passport_entities import (+ EndUserRecord,+ WebAppLoginClaims,+ WebAppRecord,+ WebPassportEndUserResolution,+ WebPassportRequest,+ WebPassportResult,+)+++class WebAppAuthType(StrEnum):+ PUBLIC = "public"+ INTERNAL = "internal"+ EXTERNAL = "external"+++class WebPassportNotFoundError(Exception):+ pass+++class WebPassportUnauthorizedError(Exception):+ pass+++class WebPassportAuthenticationRequiredError(Exception):+ pass+++class WebPassportRepository(Protocol):+ def get_active_web_app(self, app_code: str) -> WebAppRecord | None: ...++ def is_web_app_active(self, app: WebAppRecord) -> bool: ...++ def resolve_standard_end_user(self, app: WebAppRecord, session_id: str | None) -> WebPassportEndUserResolution: ...++ def resolve_authenticated_end_user(+ self,+ app: WebAppRecord,+ *,+ end_user_id: str | None,+ session_id: str | None,+ ) -> WebPassportEndUserResolution: ...+++class WebPassportAuthGateway(Protocol):+ def is_webapp_auth_enabled(self) -> bool: ...++ def get_app_auth_type(self, app_id: str) -> WebAppAuthType: ...+++class WebPassportTokenGateway(Protocol):+ def verify(self, token: str) -> Mapping[str, Any]: ...++ def issue(self, payload: Mapping[str, Any]) -> str: ...+++class WebPassportService:+ def __init__(+ self,+ *,+ passports: WebPassportRepository,+ auth: WebPassportAuthGateway,+ tokens: WebPassportTokenGateway,+ now: Callable[[], datetime],+ access_token_expire_minutes: int,+ ) -> None:+ self._passports = passports+ self._auth = auth+ self._tokens = tokens+ self._now = now+ self._access_token_expire_minutes = access_token_expire_minutes++ def issue(self, request: WebPassportRequest) -> WebPassportResult:+ app = self._passports.get_active_web_app(request.app_code)+ if app is None:+ raise WebPassportNotFoundError()++ login_claims: WebAppLoginClaims | None = None+ if self._auth.is_webapp_auth_enabled():+ login_claims = self._decode_login_token(request.access_token)+ auth_type = self._auth.get_app_auth_type(app.app_id)+ if auth_type != WebAppAuthType.PUBLIC:+ if login_claims is None:+ raise WebPassportAuthenticationRequiredError("Web app authentication required.")+ self._require_active_web_app(app)+ return self._exchange_enterprise_token(app, login_claims, auth_type)++ end_user = self._resolve_standard_user(app, request.user_session_id)+ token = self._tokens.issue(+ {+ "iss": app.app_id,+ "sub": "Web API Passport",+ "app_id": app.app_id,+ "app_code": app.app_code,+ "end_user_id": end_user.id,+ }+ )+ return WebPassportResult(access_token=token)++ def _decode_login_token(self, token: str | None) -> WebAppLoginClaims | None:+ if not token:+ return None++ decoded = self._tokens.verify(token)+ try:+ claims = WebAppLoginClaims.model_validate(decoded)+ except ValidationError as exc:+ raise WebPassportUnauthorizedError("Invalid web app login token.") from exc++ if claims.token_source != "webapp_login_token":+ raise WebPassportUnauthorizedError("Invalid token source. Expected 'webapp_login_token'.")+ return claims++ def _resolve_standard_user(self, app: WebAppRecord, session_id: str | None) -> EndUserRecord:+ resolution = self._passports.resolve_standard_end_user(app, session_id)+ self._require_active_resolution(resolution)+ if resolution.end_user is None:+ raise WebPassportNotFoundError()+ return resolution.end_user++ def _exchange_enterprise_token(+ self,+ app: WebAppRecord,+ claims: WebAppLoginClaims,+ auth_type: WebAppAuthType,+ ) -> WebPassportResult:+ user_auth_type = claims.auth_type+ if not user_auth_type:+ raise WebPassportUnauthorizedError("Missing auth_type in the token.")++ if auth_type == WebAppAuthType.EXTERNAL and user_auth_type != WebAppAuthType.EXTERNAL:+ raise WebPassportAuthenticationRequiredError("Please login as external user.")+ if auth_type == WebAppAuthType.INTERNAL and user_auth_type != WebAppAuthType.INTERNAL:+ raise WebPassportAuthenticationRequiredError("Please login as internal user.")++ resolution = self._passports.resolve_authenticated_end_user(+ app,+ end_user_id=claims.end_user_id,+ session_id=claims.session_id,+ )+ self._require_active_resolution(resolution)+ if resolution.end_user is None:+ if not claims.session_id:+ raise WebPassportNotFoundError("Missing session_id for existing web user.")+ raise WebPassportNotFoundError()+ end_user = resolution.end_user++ now = self._now()+ expires_at = int((now + timedelta(minutes=self._access_token_expire_minutes)).timestamp())+ if claims.exp:+ expires_at = int(claims.exp)++ token = self._tokens.issue(+ {+ "iss": app.site_id,+ "sub": "Web API Passport",+ "app_id": app.app_id,+ "app_code": app.app_code,+ "user_id": claims.user_id,+ "end_user_id": end_user.id,+ "auth_type": user_auth_type,+ "granted_at": int(now.timestamp()),+ "token_source": "webapp",+ "exp": expires_at,+ }+ )+ return WebPassportResult(access_token=token)++ def _require_active_web_app(self, app: WebAppRecord) -> None:+ if not self._passports.is_web_app_active(app):+ raise WebPassportNotFoundError()++ @staticmethod+ def _require_active_resolution(resolution: WebPassportEndUserResolution) -> None:+ if not resolution.app_active:+ raise WebPassportNotFoundError()diff --git a/api/services/webapp_auth_service.py b/api/services/webapp_auth_service.pyindex d05f04f7dd4..600c2b5e84f 100644--- a/api/services/webapp_auth_service.py+++ b/api/services/webapp_auth_service.py@@ -1,4 +1,3 @@-import enumimport secretsfrom datetime import UTC, datetime, timedeltafrom typing import Any@@ -16,19 +15,11 @@ from models.enums import EndUserTypefrom models.model import App, EndUser, Sitefrom services.account_service import AccountServicefrom services.app_service import AppService-from services.enterprise.enterprise_service import PERMISSION_CHECK_MODES, EnterpriseService, WebAppAccessMode+from services.enterprise.enterprise_service import PERMISSION_CHECK_MODES, EnterpriseServicefrom services.errors.account import AccountLoginError, AccountNotFoundError, AccountPasswordErrorfrom tasks.mail_email_code_login import send_email_code_login_mail_task-class WebAppAuthType(enum.StrEnum):- """Enum for web app authentication types."""-- PUBLIC = "public"- INTERNAL = "internal"- EXTERNAL = "external"--class WebAppAuthService:"""Service for web app authentication."""@@ -156,28 +147,3 @@ class WebAppAuthService:if webapp_settings and webapp_settings.access_mode in PERMISSION_CHECK_MODES:return Truereturn False-- @classmethod- def get_app_auth_type(- cls, app_code: str | None = None, access_mode: str | None = None, *, session: Session- ) -> WebAppAuthType:- """- Get the authentication type for the app based on its access mode.- """- if not app_code and not access_mode:- raise ValueError("Either app_code or access_mode must be provided.")-- if access_mode:- if access_mode == WebAppAccessMode.PUBLIC:- return WebAppAuthType.PUBLIC- elif access_mode in PERMISSION_CHECK_MODES:- return WebAppAuthType.INTERNAL- elif access_mode == WebAppAccessMode.SSO_VERIFIED:- return WebAppAuthType.EXTERNAL-- if app_code:- app_id = AppService.get_app_id_by_code(app_code, session=session)- webapp_settings = EnterpriseService.WebAppAuth.get_app_access_mode_by_id(app_id=app_id)- return cls.get_app_auth_type(access_mode=webapp_settings.access_mode, session=session)-- raise ValueError("Could not determine app authentication type.")diff --git a/api/services/workflow_service.py b/api/services/workflow_service.pyindex d7e8a2c1614..571819ff9a3 100644--- a/api/services/workflow_service.py+++ b/api/services/workflow_service.py@@ -94,6 +94,7 @@ from services.errors.app import (WorkflowHashNotEqualError,WorkflowNotFoundError,)+from services.system_feature_service import SystemFeatureServicefrom tasks.new_agent_beta_task import register_new_agent_beta_workflow_publish_after_commit@@ -700,9 +701,7 @@ class WorkflowService:)# Validate credentials before publishing, for credential policy check- from services.feature_service import FeatureService-- if FeatureService.is_plugin_manager_enabled():+ if SystemFeatureService.is_plugin_manager_enabled():self._validate_workflow_credentials(draft_workflow, session=session)# validate graph structurediff --git a/api/tasks/mail_inner_task.py b/api/tasks/mail_inner_task.pyindex d4d1ae67ce4..b556b63da98 100644--- a/api/tasks/mail_inner_task.py+++ b/api/tasks/mail_inner_task.py@@ -13,6 +13,7 @@ from configs import dify_configfrom configs.feature import TemplateModefrom extensions.ext_mail import mailfrom libs.email_i18n import get_email_i18n_service+from services.entities.mail_entities import InnerMailMessagelogger = logging.getLogger(__name__)@@ -29,7 +30,7 @@ class SandboxedEnvironment(ImmutableSandboxedEnvironment):return super().call(context, obj, *args, **kwargs)-def _render_template_with_strategy(body: str, substitutions: Mapping[str, str]) -> str:+def _render_template_with_strategy(body: str, substitutions: Mapping[str, Any]) -> str:mode = dify_config.MAIL_TEMPLATING_MODEtimeout = dify_config.MAIL_TEMPLATING_TIMEOUTif mode == TemplateMode.UNSAFE:@@ -43,7 +44,7 @@ def _render_template_with_strategy(body: str, substitutions: Mapping[str, str])@shared_task(queue="mail")-def send_inner_email_task(to: list[str], subject: str, body: str, substitutions: Mapping[str, str]):+def send_inner_email_task(to: list[str], subject: str, body: str, substitutions: Mapping[str, Any]):if not mail.is_inited():return@@ -60,3 +61,12 @@ def send_inner_email_task(to: list[str], subject: str, body: str, substitutions:logger.info(click.style(f"Send enterprise mail to {to} succeeded: latency: {end_at - start_at}", fg="green"))except Exception:logger.exception("Send enterprise mail to %s failed", to)+++def enqueue_inner_mail(message: InnerMailMessage) -> None:+ send_inner_email_task.delay(+ to=list(message.recipients),+ subject=message.subject,+ body=message.body,+ substitutions=message.substitutions or {},+ )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 248b662fd0b..cee425469e1 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@@ -21,11 +21,11 @@ from tests.test_containers_integration_tests.helpers import generate_valid_passw@pytest.fixturedef setup_dependencies() -> Iterator[MagicMock]:with (- patch("services.account_service.FeatureService") as feature_service,+ 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,):- feature_service.get_system_features.return_value.is_allow_register = True+ feature_service.is_registration_allowed.return_value = Truefeature_service.get_license.return_value.seats.is_available.return_value = Truefeature_service.get_license.return_value.workspaces.is_available.return_value = Truefeature_service.is_workspace_creation_allowed.return_value = Truediff --git a/api/tests/test_containers_integration_tests/controllers/openapi/conftest.py b/api/tests/test_containers_integration_tests/controllers/openapi/conftest.pyindex 8681f461975..d06da5bc018 100644--- a/api/tests/test_containers_integration_tests/controllers/openapi/conftest.py+++ b/api/tests/test_containers_integration_tests/controllers/openapi/conftest.py@@ -38,8 +38,8 @@ def make_account(db_session_with_containers: Session) -> Callable[..., Account]:def _make(*, with_owner_tenant: bool = True) -> Account:fake = Faker()- with patch("services.account_service.FeatureService") as mock_feature_service:- mock_feature_service.get_system_features.return_value.is_allow_register = True+ with patch("services.account_service.SystemFeatureService") as mock_feature_service:+ mock_feature_service.is_registration_allowed.return_value = Trueaccount = AccountService.create_account(email=fake.email(),name=fake.name(),@@ -60,7 +60,7 @@ 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.FeatureService") as mock_feature_service:+ with patch("services.account_service.SystemFeatureService") as mock_feature_service:mock_feature_service.is_workspace_creation_allowed.return_value = Truetenant = TenantService.create_tenant(name=name, session=session)TenantService.create_tenant_member(tenant, account, session, role=role)diff --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 4d9bfb5ea17..3e4ca88288c 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@@ -51,7 +51,7 @@ def external_deps() -> Generator[dict[str, object], None, None]:patch("services.app_dsl_service.DependenciesAnalysisService") as mock_dependencies_service,patch("services.app_dsl_service.app_was_created") as mock_app_was_created,patch("services.app_service.ModelManager.for_tenant") as mock_model_manager,- patch("services.app_service.FeatureService") as mock_feature_service,+ patch("services.app_service.SystemFeatureService") as mock_feature_service,patch("services.app_service.EnterpriseService") as mock_enterprise_service,):mock_workflow_service.return_value.get_draft_workflow.return_value = None@@ -65,7 +65,7 @@ def external_deps() -> Generator[dict[str, object], None, None]:mock_model_instance.get_default_model_instance.return_value = Nonemock_model_instance.get_default_provider_model_name.return_value = ("openai", "gpt-3.5-turbo")- mock_feature_service.get_system_features.return_value.webapp_auth.enabled = False+ mock_feature_service.is_webapp_auth_enabled.return_value = Falsemock_enterprise_service.WebAppAuth.update_app_access_mode.return_value = Nonemock_enterprise_service.WebAppAuth.cleanup_webapp.return_value = None@@ -74,8 +74,8 @@ 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.FeatureService") as mock_account_feature_service:- mock_account_feature_service.get_system_features.return_value.is_allow_register = True+ with patch("services.account_service.SystemFeatureService") as mock_account_feature_service:+ mock_account_feature_service.is_registration_allowed.return_value = Trueaccount = AccountService.create_account(email=fake.email(),name=fake.name(),diff --git a/api/tests/test_containers_integration_tests/controllers/web/test_wraps.py b/api/tests/test_containers_integration_tests/controllers/web/test_wraps.pyindex 01e241a9b94..9a143ab3bc3 100644--- a/api/tests/test_containers_integration_tests/controllers/web/test_wraps.py+++ b/api/tests/test_containers_integration_tests/controllers/web/test_wraps.py@@ -231,7 +231,7 @@ class TestDecodeJwtToken:@patch("controllers.web.wraps._validate_webapp_token")@patch("controllers.web.wraps.EnterpriseService.WebAppAuth.get_app_access_mode_by_id")@patch("controllers.web.wraps.AppService.get_app_id_by_code")- @patch("controllers.web.wraps.FeatureService.get_system_features")+ @patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")@patch("controllers.web.wraps.PassportService")@patch("controllers.web.wraps.extract_webapp_passport")def test_happy_path(@@ -254,7 +254,7 @@ class TestDecodeJwtToken:"app_id": app_model.id,"end_user_id": end_user.id,}- mock_features.return_value = SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False))+ mock_features.return_value = Falsewith app.test_request_context("/", headers={"X-App-Code": site.code}):result_app, result_user = decode_jwt_token()@@ -262,17 +262,17 @@ class TestDecodeJwtToken:assert result_app.id == app_model.idassert result_user.id == end_user.id- @patch("controllers.web.wraps.FeatureService.get_system_features")+ @patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")@patch("controllers.web.wraps.extract_webapp_passport")def test_missing_token_raises_unauthorized(self, mock_extract: MagicMock, mock_features: MagicMock, app) -> None:- mock_features.return_value = SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False))+ mock_features.return_value = Falsemock_extract.return_value = Nonewith app.test_request_context("/", headers={"X-App-Code": "code1"}):with pytest.raises(Unauthorized):decode_jwt_token()- @patch("controllers.web.wraps.FeatureService.get_system_features")+ @patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")@patch("controllers.web.wraps.PassportService")@patch("controllers.web.wraps.extract_webapp_passport")def test_missing_app_raises_not_found(@@ -289,13 +289,13 @@ class TestDecodeJwtToken:"app_id": non_existent_id,"end_user_id": str(uuid4()),}- mock_features.return_value = SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False))+ mock_features.return_value = Falsewith app.test_request_context("/", headers={"X-App-Code": "code1"}):with pytest.raises(NotFound):decode_jwt_token()- @patch("controllers.web.wraps.FeatureService.get_system_features")+ @patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")@patch("controllers.web.wraps.PassportService")@patch("controllers.web.wraps.extract_webapp_passport")def test_disabled_site_raises_bad_request(@@ -314,13 +314,13 @@ class TestDecodeJwtToken:"app_id": app_model.id,"end_user_id": end_user.id,}- mock_features.return_value = SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False))+ mock_features.return_value = Falsewith app.test_request_context("/", headers={"X-App-Code": site.code}):with pytest.raises(BadRequest, match="Site is disabled"):decode_jwt_token()- @patch("controllers.web.wraps.FeatureService.get_system_features")+ @patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")@patch("controllers.web.wraps.PassportService")@patch("controllers.web.wraps.extract_webapp_passport")def test_missing_end_user_raises_not_found(@@ -340,13 +340,13 @@ class TestDecodeJwtToken:"app_id": app_model.id,"end_user_id": non_existent_eu,}- mock_features.return_value = SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False))+ mock_features.return_value = Falsewith app.test_request_context("/", headers={"X-App-Code": site.code}):with pytest.raises(NotFound):decode_jwt_token()- @patch("controllers.web.wraps.FeatureService.get_system_features")+ @patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")@patch("controllers.web.wraps.PassportService")@patch("controllers.web.wraps.extract_webapp_passport")def test_user_id_mismatch_raises_unauthorized(@@ -365,7 +365,7 @@ class TestDecodeJwtToken:"app_id": app_model.id,"end_user_id": end_user.id,}- mock_features.return_value = SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False))+ mock_features.return_value = Falsewith app.test_request_context("/", headers={"X-App-Code": site.code}):with pytest.raises(Unauthorized, match="expired"):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 1b9a39ac891..44d7e2e4d21 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@@ -626,10 +626,10 @@ class TestKnowledgeRetrievalIntegration:@pytest.fixturedef mock_external_service_dependencies():with (- patch("services.account_service.FeatureService") as mock_account_feature_service,+ patch("services.account_service.SystemFeatureService") as mock_account_feature_service,):# Setup default mock returns for account service- mock_account_feature_service.get_system_features.return_value.is_allow_register = True+ mock_account_feature_service.is_registration_allowed.return_value = Trueyield {"account_feature_service": mock_account_feature_service,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.pyindex db538d78c13..80000b06f13 100644--- a/api/tests/test_containers_integration_tests/services/test_account_service.py+++ b/api/tests/test_containers_integration_tests/services/test_account_service.py@@ -30,12 +30,12 @@ class TestAccountService:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.account_service.FeatureService") as mock_feature_service,+ 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.get_system_features.return_value.is_allow_register = True+ mock_feature_service.is_registration_allowed.return_value = Truemock_feature_service.is_workspace_creation_allowed.return_value = Truemock_feature_service.get_license.return_value.workspaces.is_available.return_value = Truemock_feature_service.get_license.return_value.seats.is_available.return_value = True@@ -57,7 +57,7 @@ class TestAccountService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falseaccount = AccountService.create_account(@@ -84,7 +84,7 @@ class TestAccountService:email = fake.email()name = fake.name()# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falseaccount = AccountService.create_account(@@ -108,7 +108,7 @@ class TestAccountService:email = fake.email()name = fake.name()# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Test with too short password (assuming minimum length validation)@@ -131,7 +131,7 @@ class TestAccountService:email = fake.email()name = fake.name()# Setup mocks to disable registration- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = False+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Falsewith pytest.raises(AccountNotFound): # AccountNotFound exceptionAccountService.create_account(@@ -153,7 +153,7 @@ class TestAccountService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Truedify_config.DEPLOYMENT_EDITION = DeploymentEdition.CLOUD@@ -189,7 +189,7 @@ class TestAccountService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create account first@@ -219,7 +219,7 @@ class TestAccountService:correct_password = generate_valid_password(fake)wrong_password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create account first@@ -245,7 +245,7 @@ class TestAccountService:name = fake.name()new_password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create account without password@@ -280,7 +280,7 @@ class TestAccountService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create account with pending status@@ -309,7 +309,7 @@ class TestAccountService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = Truemock_external_service_dependencies["feature_service"@@ -342,7 +342,7 @@ class TestAccountService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = Falsemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False@@ -366,7 +366,7 @@ class TestAccountService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = Truemock_external_service_dependencies["feature_service"@@ -393,7 +393,7 @@ class TestAccountService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["feature_service"].get_license.return_value.seats.is_available.return_value = False@@ -418,7 +418,7 @@ class TestAccountService:email = fake.email()name = fake.name()# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create account@@ -456,7 +456,7 @@ class TestAccountService:email = fake.email()name = fake.name()# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create account@@ -498,7 +498,7 @@ class TestAccountService:password = generate_valid_password(fake)ip_address = fake.ipv4()# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create account@@ -529,7 +529,7 @@ class TestAccountService:password = generate_valid_password(fake)ip_address = fake.ipv4()# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsemock_external_service_dependencies["passport_service"].return_value.issue.return_value = "mock_access_token"@@ -568,7 +568,7 @@ class TestAccountService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsemock_external_service_dependencies["passport_service"].return_value.issue.return_value = "mock_access_token"@@ -599,7 +599,7 @@ class TestAccountService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsemock_external_service_dependencies["passport_service"].return_value.issue.return_value = "mock_access_token"@@ -634,7 +634,7 @@ class TestAccountService:password = generate_valid_password(fake)tenant_name = fake.company()# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsemock_external_service_dependencies["passport_service"].return_value.issue.return_value = "new_mock_access_token"@@ -683,7 +683,7 @@ class TestAccountService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsemock_external_service_dependencies["passport_service"].return_value.issue.return_value = "mock_access_token"@@ -718,7 +718,7 @@ class TestAccountService:password = generate_valid_password(fake)tenant_name = fake.company()# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create account@@ -759,7 +759,7 @@ class TestAccountService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create account@@ -788,7 +788,7 @@ class TestAccountService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsemock_external_service_dependencies["passport_service"].return_value.issue.return_value = "mock_jwt_token"@@ -824,7 +824,7 @@ class TestAccountService:password = generate_valid_password(fake)tenant_name = fake.company()# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create account@@ -859,7 +859,7 @@ class TestAccountService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create account@@ -900,7 +900,7 @@ class TestAccountService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create account@@ -946,7 +946,7 @@ class TestTenantService:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.account_service.FeatureService") as mock_feature_service,+ patch("services.account_service.SystemFeatureService") as mock_feature_service,patch("services.account_service.BillingService") as mock_billing_service,):# Setup default mock returns@@ -2038,12 +2038,12 @@ class TestRegisterService:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.account_service.FeatureService") as mock_feature_service,+ 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.get_system_features.return_value.is_allow_register = True+ mock_feature_service.is_registration_allowed.return_value = Truemock_feature_service.is_workspace_creation_allowed.return_value = Truemock_feature_service.get_license.return_value.workspaces.is_available.return_value = Truemock_feature_service.get_license.return_value.seats.is_available.return_value = True@@ -2066,7 +2066,7 @@ class TestRegisterService:admin_password = generate_valid_password(fake)ip_address = fake.ipv4()# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsefrom models.model import DifySetup@@ -2115,7 +2115,7 @@ class TestRegisterService:admin_password = generate_valid_password(fake)ip_address = fake.ipv4()# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Mock AccountService.create_account to raise exception@@ -2157,7 +2157,7 @@ class TestRegisterService:password = generate_valid_password(fake)language = fake.random_element(elements=("en-US", "zh-CN"))# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = Truemock_external_service_dependencies["feature_service"@@ -2199,7 +2199,7 @@ class TestRegisterService:provider = fake.random_element(elements=("google", "github", "microsoft"))language = fake.random_element(elements=("en-US", "zh-CN"))# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = Truemock_external_service_dependencies["feature_service"@@ -2246,7 +2246,7 @@ class TestRegisterService:password = generate_valid_password(fake)language = fake.random_element(elements=("en-US", "zh-CN"))# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = Truemock_external_service_dependencies["feature_service"@@ -2290,7 +2290,7 @@ class TestRegisterService:password = generate_valid_password(fake)language = fake.random_element(elements=("en-US", "zh-CN"))# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = Falsemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False@@ -2327,7 +2327,7 @@ class TestRegisterService:password = generate_valid_password(fake)language = fake.random_element(elements=("en-US", "zh-CN"))# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = Truemock_external_service_dependencies["feature_service"@@ -2365,7 +2365,7 @@ class TestRegisterService:password = generate_valid_password(fake)language = fake.random_element(elements=("en-US", "zh-CN"))# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Execute registration without workspace creation@@ -2404,7 +2404,7 @@ class TestRegisterService:new_member_email = fake.email()language = fake.random_element(elements=("en-US", "zh-CN"))# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = Truemock_external_service_dependencies["feature_service"@@ -2476,7 +2476,7 @@ class TestRegisterService:existing_member_password = generate_valid_password(fake)language = fake.random_element(elements=("en-US", "zh-CN"))# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create tenant and inviter account@@ -2550,7 +2550,7 @@ class TestRegisterService: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"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create tenant and inviter account@@ -2611,7 +2611,7 @@ class TestRegisterService:new_member_email = fake.email()language = fake.random_element(elements=("en-US", "zh-CN"))# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create tenant@@ -2644,7 +2644,7 @@ class TestRegisterService: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"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create tenant and inviter account@@ -2696,7 +2696,7 @@ class TestRegisterService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create tenant and account@@ -2741,7 +2741,7 @@ class TestRegisterService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create tenant and account@@ -2789,7 +2789,7 @@ class TestRegisterService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create tenant and account@@ -2833,7 +2833,7 @@ class TestRegisterService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create tenant and account@@ -2877,7 +2877,7 @@ class TestRegisterService:name = fake.name()password = generate_valid_password(fake)# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create tenant and account@@ -2950,7 +2950,7 @@ class TestRegisterService:invalid_tenant_id = fake.uuid4()token = fake.uuid4()# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create account@@ -3002,7 +3002,7 @@ class TestRegisterService:password = generate_valid_password(fake)token = fake.uuid4()# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create tenant and account@@ -3054,7 +3054,7 @@ class TestRegisterService:password = generate_valid_password(fake)token = fake.uuid4()# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Create tenant and accountdiff --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 445f2704641..d6e0ff103c1 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@@ -26,10 +26,10 @@ class TestAgentService:patch("services.agent_service.ToolManager", autospec=True) as mock_tool_manager,patch("services.agent_service.AgentConfigManager", autospec=True) as mock_agent_config_manager,patch("services.agent_service.current_user", create_autospec(Account, instance=True)) as mock_current_user,- patch("services.app_service.FeatureService", autospec=True) as mock_feature_service,+ 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.FeatureService", autospec=True) as mock_account_feature_service,+ patch("services.account_service.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@@ -67,12 +67,12 @@ class TestAgentService:mock_current_user.timezone = "UTC"# Setup default mock returns for app service- mock_feature_service.get_system_features.return_value.webapp_auth.enabled = False+ mock_feature_service.is_webapp_auth_enabled.return_value = Falsemock_enterprise_service.WebAppAuth.update_app_access_mode.return_value = Nonemock_enterprise_service.WebAppAuth.cleanup_webapp.return_value = None# Setup default mock returns for account service- mock_account_feature_service.get_system_features.return_value.is_allow_register = True+ mock_account_feature_service.is_registration_allowed.return_value = True# Mock ModelManager for model configurationmock_model_instance = mock_model_manager.return_value@@ -104,9 +104,7 @@ class TestAgentService:fake = Faker()# Setup mocks for account creation- mock_external_service_dependencies[- "account_feature_service"- ].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenantaccount = AccountService.create_account(diff --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 b416aee33fe..f9e66d91e78 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@@ -21,7 +21,7 @@ class TestAnnotationService:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.account_service.FeatureService") as mock_account_feature_service,+ patch("services.account_service.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,@@ -70,9 +70,7 @@ class TestAnnotationService:fake = Faker()# Setup mocks for account creation- mock_external_service_dependencies[- "account_feature_service"- ].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenant firstfrom services.account_service import AccountService, TenantServicediff --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 de51f5077e6..ba0a3c2707a 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@@ -17,7 +17,7 @@ class TestAPIBasedExtensionService:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.account_service.FeatureService") as mock_account_feature_service,+ patch("services.account_service.SystemFeatureService") as mock_account_feature_service,patch("services.api_based_extension_service.APIBasedExtensionRequestor") as mock_requestor,):# Setup default mock returns@@ -47,9 +47,7 @@ class TestAPIBasedExtensionService:fake = Faker()# Setup mocks for account creation- mock_external_service_dependencies[- "account_feature_service"- ].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenantaccount = AccountService.create_account(diff --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 e61b22e611a..eea8ab9c2a8 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@@ -122,7 +122,7 @@ class TestAppDslService:patch("services.app_dsl_service.DependenciesAnalysisService") as mock_dependencies_service,patch("services.app_dsl_service.app_was_created") as mock_app_was_created,patch("services.app_service.ModelManager.for_tenant") as mock_model_manager,- patch("services.app_service.FeatureService") as mock_feature_service,+ patch("services.app_service.SystemFeatureService") as mock_feature_service,patch("services.app_service.EnterpriseService") as mock_enterprise_service,):mock_workflow_service.return_value.get_draft_workflow.return_value = None@@ -139,7 +139,7 @@ class TestAppDslService:"gpt-3.5-turbo",)- mock_feature_service.get_system_features.return_value.webapp_auth.enabled = False+ mock_feature_service.is_webapp_auth_enabled.return_value = Falsemock_enterprise_service.WebAppAuth.update_app_access_mode.return_value = Nonemock_enterprise_service.WebAppAuth.cleanup_webapp.return_value = Noneyield {@@ -153,8 +153,8 @@ 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.FeatureService") as mock_account_feature_service:- mock_account_feature_service.get_system_features.return_value.is_allow_register = True+ with patch("services.account_service.SystemFeatureService") as mock_account_feature_service:+ mock_account_feature_service.is_registration_allowed.return_value = Trueaccount = AccountService.create_account(email=fake.email(),name=fake.name(),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 d9f81caf01c..7e27e66f10c 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@@ -38,7 +38,7 @@ class TestAppGenerateService:patch("services.app_generate_service.MessageBasedAppGenerator", autospec=True) as mock_message_based_generator,- patch("services.account_service.FeatureService", autospec=True) as mock_account_feature_service,+ patch("services.account_service.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,@@ -104,7 +104,7 @@ class TestAppGenerateService:mock_message_based_generator.retrieve_events.return_value = ["workflow_events"]# Setup default mock returns for account service- mock_account_feature_service.get_system_features.return_value.is_allow_register = True+ mock_account_feature_service.is_registration_allowed.return_value = True# Setup dify_config mock returnsmock_dify_config.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITY@@ -155,9 +155,7 @@ class TestAppGenerateService:fake = Faker()# Setup mocks for account creation- mock_external_service_dependencies[- "account_feature_service"- ].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenantfrom services.account_service import AccountService, TenantServicediff --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 44006359acd..4c50966777d 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@@ -25,18 +25,18 @@ class TestAppService:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.app_service.FeatureService") as mock_feature_service,+ 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.FeatureService") as mock_account_feature_service,+ patch("services.account_service.SystemFeatureService") as mock_account_feature_service,):# Setup default mock returns for app service- mock_feature_service.get_system_features.return_value.webapp_auth.enabled = False+ mock_feature_service.is_webapp_auth_enabled.return_value = Falsemock_enterprise_service.WebAppAuth.update_app_access_mode.return_value = Nonemock_enterprise_service.WebAppAuth.cleanup_webapp.return_value = None# Setup default mock returns for account service- mock_account_feature_service.get_system_features.return_value.is_allow_register = True+ mock_account_feature_service.is_registration_allowed.return_value = True# Mock ModelManager for model configurationmock_model_instance = mock_model_manager.return_value@@ -1252,9 +1252,7 @@ class TestAppService:app_id = app.id# Mock webapp auth cleanup- mock_external_service_dependencies[- "feature_service"- ].get_system_features.return_value.webapp_auth.enabled = True+ mock_external_service_dependencies["feature_service"].is_webapp_auth_enabled.return_value = True# Mock the async deletion taskwith patch("services.app_service.remove_app_and_related_data_task") as mock_delete_task:diff --git a/api/tests/test_containers_integration_tests/services/test_feature_service.py b/api/tests/test_containers_integration_tests/services/test_feature_service.pyindex ca933a08462..99c8dd9b322 100644--- a/api/tests/test_containers_integration_tests/services/test_feature_service.py+++ b/api/tests/test_containers_integration_tests/services/test_feature_service.py@@ -14,6 +14,7 @@ from services.entities.feature_entities import (SystemFeatureModel,)from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServiceclass TestFeatureService:@@ -25,6 +26,7 @@ class TestFeatureService:with (patch("services.feature_service.BillingService") as mock_billing_service,patch("services.feature_service.EnterpriseService") as mock_enterprise_service,+ patch("services.system_feature_service.EnterpriseService", new=mock_enterprise_service),):# Setup default mock returns for BillingServicemock_billing_service.get_info.return_value = {@@ -273,7 +275,7 @@ class TestFeatureService:# Arrange: Setup test data with proper configtenant_id = self._create_test_tenant_id()- with patch("services.feature_service.dify_config") as mock_config:+ with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.MARKETPLACE_ENABLED = Truemock_config.ENABLE_EMAIL_CODE_LOGIN = True@@ -285,7 +287,7 @@ class TestFeatureService:mock_config.MAIL_TYPE = "smtp"# Act: Execute the method under test- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()# Assert: Verify the expected outcomesassert result is not None@@ -345,7 +347,7 @@ class TestFeatureService:- The response structure adheres to the public schema for unauthenticated clients."""# Arrange: Setup test data with exact same config as success test- with patch("services.feature_service.dify_config") as mock_config:+ with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.MARKETPLACE_ENABLED = Truemock_config.ENABLE_EMAIL_CODE_LOGIN = True@@ -357,7 +359,7 @@ class TestFeatureService:mock_config.PLUGIN_MAX_PACKAGE_SIZE = 100# Act: Execute the public (unauthenticated) system-features call- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()# Assert: Basic structureassert result is not None@@ -399,11 +401,11 @@ class TestFeatureService:- Detail withheld from the public system-features model is present here."""# Arrange- with patch("services.feature_service.dify_config") as mock_config:+ with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISE# Act- result = FeatureService.get_license()+ result = SystemFeatureService.get_license()# Assert: full license detail is populatedassert isinstance(result, LicenseModel)@@ -418,10 +420,10 @@ class TestFeatureService:self, db_session_with_containers: Session, mock_external_service_dependencies):"""Non-enterprise deployments have no license, so limits are unconstrained."""- with patch("services.feature_service.dify_config") as mock_config:+ with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITY- result = FeatureService.get_license()+ result = SystemFeatureService.get_license()assert isinstance(result, LicenseModel)assert result.status == LicenseStatus.NONE@@ -442,7 +444,7 @@ class TestFeatureService:- Return value correctness and structure"""# Arrange: Setup basic config mock (no enterprise)- with patch("services.feature_service.dify_config") as mock_config:+ with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITYmock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = True@@ -456,7 +458,7 @@ class TestFeatureService:mock_config.PLUGIN_MAX_PACKAGE_SIZE = 100# Act: Execute the method under test- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()# Assert: Verify the expected outcomesassert result is not None@@ -640,7 +642,7 @@ class TestFeatureService:- Return value correctness and structure"""# Arrange: Use the Community edition.- with patch("services.feature_service.dify_config") as mock_config:+ with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.COMMUNITYmock_config.MARKETPLACE_ENABLED = Truemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -653,7 +655,7 @@ class TestFeatureService:mock_config.PLUGIN_MAX_PACKAGE_SIZE = 50# Act: Execute the method under test- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()# Assert: Verify the expected outcomesassert result is not None@@ -863,7 +865,7 @@ class TestFeatureService:- Return value correctness and structure"""# Arrange: Setup edge case webapp auth mock with proper config- with patch("services.feature_service.dify_config") as mock_config:+ with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -879,7 +881,7 @@ class TestFeatureService:}# Act: Execute the method under test- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()# Assert: Verify the expected outcomesassert result is not None@@ -981,7 +983,7 @@ class TestFeatureService:"""# Test case 1: Official only scope- with patch("services.feature_service.dify_config") as mock_config:+ with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -999,12 +1001,12 @@ class TestFeatureService:}}- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()assert result.plugin_installation_permission.plugin_installation_scope == "official_only"assert result.plugin_installation_permission.restrict_to_marketplace_only is True# Test case 2: All plugins scope- with patch("services.feature_service.dify_config") as mock_config:+ with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -1019,12 +1021,12 @@ class TestFeatureService:"PluginInstallationPermission": {"pluginInstallationScope": "all", "restrictToMarketplaceOnly": False}}- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()assert result.plugin_installation_permission.plugin_installation_scope == "all"assert result.plugin_installation_permission.restrict_to_marketplace_only is False# Test case 3: Specific partners scope- with patch("services.feature_service.dify_config") as mock_config:+ with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -1042,12 +1044,12 @@ class TestFeatureService:}}- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()assert result.plugin_installation_permission.plugin_installation_scope == "official_and_specific_partners"assert result.plugin_installation_permission.restrict_to_marketplace_only is False# Test case 4: None scope- with patch("services.feature_service.dify_config") as mock_config:+ with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -1062,7 +1064,7 @@ class TestFeatureService:"PluginInstallationPermission": {"pluginInstallationScope": "none", "restrictToMarketplaceOnly": True}}- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()assert result.plugin_installation_permission.plugin_installation_scope == "none"assert result.plugin_installation_permission.restrict_to_marketplace_only is True@@ -1120,7 +1122,7 @@ class TestFeatureService:- Return value correctness and structure"""# Arrange: Setup inactive license mock with proper config- with patch("services.feature_service.dify_config") as mock_config:+ with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -1140,7 +1142,7 @@ class TestFeatureService:}# Act: Execute the authenticated license accessor- result = FeatureService.get_license()+ result = SystemFeatureService.get_license()# Assert: Verify the expected outcomesassert result is not None@@ -1169,7 +1171,7 @@ class TestFeatureService:- Return value correctness and structure"""# Arrange: Setup partial enterprise info mock with proper config- with patch("services.feature_service.dify_config") as mock_config:+ with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -1187,7 +1189,7 @@ class TestFeatureService:}# Act: Execute the method under test- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()# Assert: Verify the expected outcomesassert result is not None@@ -1297,7 +1299,7 @@ class TestFeatureService:- Return value correctness and structure"""# Arrange: Setup edge case protocols mock with proper config- with patch("services.feature_service.dify_config") as mock_config:+ with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -1315,7 +1317,7 @@ class TestFeatureService:}# Act: Execute the method under test- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()# Assert: Verify the expected outcomesassert result is not None@@ -1448,7 +1450,7 @@ class TestFeatureService:- Return value correctness and structure"""# Arrange: Setup expired license mock with proper config- with patch("services.feature_service.dify_config") as mock_config:+ with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -1468,7 +1470,7 @@ class TestFeatureService:}# Act: Execute the authenticated license accessor- result = FeatureService.get_license()+ result = SystemFeatureService.get_license()# Assert: Verify the expected outcomesassert result is not None@@ -1554,7 +1556,7 @@ class TestFeatureService:- Return value correctness and structure"""# Arrange: Setup edge case branding mock with proper config- with patch("services.feature_service.dify_config") as mock_config:+ with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -1575,7 +1577,7 @@ class TestFeatureService:}# Act: Execute the method under test- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()# Assert: Verify the expected outcomesassert result is not None@@ -1740,7 +1742,7 @@ class TestFeatureService:- Return value correctness and structure"""# Arrange: Setup lost license mock with proper config- with patch("services.feature_service.dify_config") as mock_config:+ with patch("services.system_feature_service.dify_config") as mock_config:mock_config.DEPLOYMENT_EDITION = DeploymentEdition.ENTERPRISEmock_config.MARKETPLACE_ENABLED = Falsemock_config.ENABLE_EMAIL_CODE_LOGIN = False@@ -1756,7 +1758,7 @@ class TestFeatureService:}# Act: Execute the method under test- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()# Assert: Verify the expected outcomesassert result is not Nonediff --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 702812b96de..62d03690ee9 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.FeatureService") as mock_account_feature_service,+ patch("services.account_service.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,@@ -86,9 +86,7 @@ class TestMessageService:fake = Faker()# Setup mocks for account creation- mock_external_service_dependencies[- "account_feature_service"- ].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenant firstfrom services.account_service import AccountService, TenantServicediff --git a/api/tests/test_containers_integration_tests/services/test_ops_service.py b/api/tests/test_containers_integration_tests/services/test_ops_service.pyindex b4b8521fb2e..029c6ba9420 100644--- a/api/tests/test_containers_integration_tests/services/test_ops_service.py+++ b/api/tests/test_containers_integration_tests/services/test_ops_service.py@@ -20,15 +20,15 @@ class TestOpsService:@pytest.fixturedef mock_external_service_dependencies(self):with (- patch("services.app_service.FeatureService") as mock_feature_service,+ 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.FeatureService") as mock_account_feature_service,+ patch("services.account_service.SystemFeatureService") as mock_account_feature_service,):- mock_feature_service.get_system_features.return_value.webapp_auth.enabled = False+ mock_feature_service.is_webapp_auth_enabled.return_value = Falsemock_enterprise_service.WebAppAuth.update_app_access_mode.return_value = Nonemock_enterprise_service.WebAppAuth.cleanup_webapp.return_value = None- mock_account_feature_service.get_system_features.return_value.is_allow_register = True+ mock_account_feature_service.is_registration_allowed.return_value = Truemock_model_instance = mock_model_manager.return_valuemock_model_instance.get_default_model_instance.return_value = Nonemock_model_instance.get_default_provider_model_name.return_value = ("openai", "gpt-3.5-turbo")diff --git a/api/tests/test_containers_integration_tests/services/test_saved_message_service.py b/api/tests/test_containers_integration_tests/services/test_saved_message_service.pyindex 92741ac56cb..a55ed6c9532 100644--- a/api/tests/test_containers_integration_tests/services/test_saved_message_service.py+++ b/api/tests/test_containers_integration_tests/services/test_saved_message_service.py@@ -20,12 +20,12 @@ class TestSavedMessageService:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.account_service.FeatureService") as mock_account_feature_service,+ patch("services.account_service.SystemFeatureService") as mock_account_feature_service,patch("services.app_service.ModelManager.for_tenant") as mock_model_manager,patch("services.saved_message_service.MessageService") as mock_message_service,):# Setup default mock returns- mock_account_feature_service.get_system_features.return_value.is_allow_register = True+ mock_account_feature_service.is_registration_allowed.return_value = True# Mock ModelManager for app creationmock_model_instance = mock_model_manager.return_value@@ -56,9 +56,7 @@ class TestSavedMessageService:fake = Faker()# Setup mocks for account creation- mock_external_service_dependencies[- "account_feature_service"- ].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenant firstfrom services.account_service import AccountService, TenantServicediff --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 c464505ef9e..90160d5a963 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.FeatureService") as mock_account_feature_service,+ patch("services.account_service.SystemFeatureService") as mock_account_feature_service,):# Setup default mock returnsmock_provider_controller = MagicMock()@@ -42,7 +42,7 @@ class TestTriggerProviderService:mock_redis_client.lock.return_value = mock_lock# Setup account feature service mock- mock_account_feature_service.get_system_features.return_value.is_allow_register = True+ mock_account_feature_service.is_registration_allowed.return_value = Trueyield {"trigger_manager": mock_trigger_manager,@@ -71,9 +71,7 @@ class TestTriggerProviderService:from services.account_service import AccountService, TenantService# Setup mocks for account creation- mock_external_service_dependencies[- "account_feature_service"- ].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["trigger_manager"].get_trigger_provider.return_value = mock_external_service_dependencies["provider_controller"]diff --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 ed063ceaccc..484f093ed47 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@@ -23,18 +23,18 @@ class TestWebConversationService:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.app_service.FeatureService") as mock_feature_service,+ 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.FeatureService") as mock_account_feature_service,+ patch("services.account_service.SystemFeatureService") as mock_account_feature_service,):# Setup default mock returns for app service- mock_feature_service.get_system_features.return_value.webapp_auth.enabled = False+ mock_feature_service.is_webapp_auth_enabled.return_value = Falsemock_enterprise_service.WebAppAuth.update_app_access_mode.return_value = Nonemock_enterprise_service.WebAppAuth.cleanup_webapp.return_value = None# Setup default mock returns for account service- mock_account_feature_service.get_system_features.return_value.is_allow_register = True+ mock_account_feature_service.is_registration_allowed.return_value = True# Mock ModelManager for model configurationmock_model_instance = mock_model_manager.return_value@@ -62,9 +62,7 @@ class TestWebConversationService:fake = Faker()# Setup mocks for account creation- mock_external_service_dependencies[- "account_feature_service"- ].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenantaccount = AccountService.create_account(diff --git a/api/tests/test_containers_integration_tests/services/test_webapp_auth_service.py b/api/tests/test_containers_integration_tests/services/test_webapp_auth_service.pyindex d47eaa0f8c5..d63ba1190ec 100644--- a/api/tests/test_containers_integration_tests/services/test_webapp_auth_service.py+++ b/api/tests/test_containers_integration_tests/services/test_webapp_auth_service.py@@ -11,7 +11,7 @@ from libs.password import hash_passwordfrom models import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccountRolefrom models.model import App, Sitefrom services.errors.account import AccountLoginError, AccountNotFoundError, AccountPasswordError-from services.webapp_auth_service import WebAppAuthService, WebAppAuthType+from services.webapp_auth_service import WebAppAuthServicefrom tests.test_containers_integration_tests.helpers import generate_valid_password@@ -825,90 +825,3 @@ class TestWebAppAuthService:WebAppAuthService.is_app_require_permission_check(session=db_session_with_containers)assert "Either app_code or app_id must be provided." in str(exc_info.value)-- def test_get_app_auth_type_with_access_mode_public(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test app authentication type for public access mode.-- This test verifies:- - Proper authentication type determination for public mode- - Correct return value- - Mock service integration- """- # Arrange: Setup test with public access mode-- # Act: Execute authentication type determination- result = WebAppAuthService.get_app_auth_type(access_mode="public", session=db_session_with_containers)-- # Assert: Verify correct result- assert result == WebAppAuthType.PUBLIC-- def test_get_app_auth_type_with_access_mode_private(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test app authentication type for private access mode.-- This test verifies:- - Proper authentication type determination for private mode- - Correct return value- - Mock service integration- """- # Arrange: Setup test with private access mode-- # Act: Execute authentication type determination- result = WebAppAuthService.get_app_auth_type(access_mode="private", session=db_session_with_containers)-- # Assert: Verify correct result- assert result == WebAppAuthType.INTERNAL-- def test_get_app_auth_type_with_app_code(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test app authentication type using app code.-- This test verifies:- - Proper authentication type determination using app code- - Correct return value- - Mock service integration- """- # Arrange: Setup mock for enterprise service- mock_external_service_dependencies["app_service"].get_app_id_by_code.return_value = "mock_app_id"- setting = type("MockWebAppAuth", (), {"access_mode": "sso_verified"})()- mock_external_service_dependencies[- "enterprise_service"- ].WebAppAuth.get_app_access_mode_by_id.return_value = setting-- # Act: Execute authentication type determination- result: WebAppAuthType = WebAppAuthService.get_app_auth_type(- app_code="mock_app_code", session=db_session_with_containers- )-- # Assert: Verify correct result- assert result == WebAppAuthType.EXTERNAL-- # Verify mock service was called correctly- mock_external_service_dependencies[- "enterprise_service"- ].WebAppAuth.get_app_access_mode_by_id.assert_called_once_with(app_id="mock_app_id")-- def test_get_app_auth_type_no_parameters(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test app authentication type with no parameters.-- This test verifies:- - Proper error handling when no parameters provided- - Correct exception type and message- """- # Arrange: No parameters provided-- # Act & Assert: Verify proper error handling- with pytest.raises(ValueError) as exc_info:- WebAppAuthService.get_app_auth_type(session=db_session_with_containers)-- assert "Either app_code or access_mode must be provided." in str(exc_info.value)diff --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 a7a06362cad..0f67408cb03 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@@ -8,14 +8,12 @@ from faker import Fakerfrom flask import Flaskfrom sqlalchemy.orm import Session-from enums import DeploymentEditionfrom models.account import Account, Tenantfrom models.enums import AppTriggerStatus, AppTriggerTypefrom models.model import Appfrom models.trigger import AppTrigger, WorkflowWebhookTriggerfrom models.workflow import Workflowfrom services.account_service import AccountService, TenantService-from services.entities.feature_entities import SystemFeatureModelfrom services.trigger.webhook_service import WebhookServicefrom tests.test_containers_integration_tests.helpers import generate_valid_password@@ -38,16 +36,12 @@ def test_data("""Persist the webhook graph with account and workspace creation enabled."""fake = Faker()- system_features = SystemFeatureModel(- deployment_edition=DeploymentEdition.COMMUNITY,- is_allow_register=True,- )monkeypatch.setattr(- "services.account_service.FeatureService.get_system_features",- lambda: system_features,+ "services.account_service.SystemFeatureService.is_registration_allowed",+ lambda: True,)monkeypatch.setattr(- "services.account_service.FeatureService.is_workspace_creation_allowed",+ "services.account_service.SystemFeatureService.is_workspace_creation_allowed",lambda: True,)account = AccountService.create_account(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 78cdb9740ce..617c27f41a6 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@@ -28,18 +28,18 @@ class TestWorkflowAppService:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.app_service.FeatureService") as mock_feature_service,+ 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.FeatureService") as mock_account_feature_service,+ patch("services.account_service.SystemFeatureService") as mock_account_feature_service,):# Setup default mock returns for app service- mock_feature_service.get_system_features.return_value.webapp_auth.enabled = False+ mock_feature_service.is_webapp_auth_enabled.return_value = Falsemock_enterprise_service.WebAppAuth.update_app_access_mode.return_value = Nonemock_enterprise_service.WebAppAuth.cleanup_webapp.return_value = None# Setup default mock returns for account service- mock_account_feature_service.get_system_features.return_value.is_allow_register = True+ mock_account_feature_service.is_registration_allowed.return_value = True# Mock ModelManager for model configurationmock_model_instance = mock_model_manager.return_value@@ -67,9 +67,7 @@ class TestWorkflowAppService:fake = Faker()# Setup mocks for account creation- mock_external_service_dependencies[- "account_feature_service"- ].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenantaccount = AccountService.create_account(@@ -116,9 +114,7 @@ class TestWorkflowAppService:fake = Faker()# Setup mocks for account creation- mock_external_service_dependencies[- "account_feature_service"- ].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenantaccount = AccountService.create_account(diff --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 7c528f06b10..263f41e5144 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@@ -25,18 +25,18 @@ class TestWorkflowRunService:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.app_service.FeatureService") as mock_feature_service,+ 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.FeatureService") as mock_account_feature_service,+ patch("services.account_service.SystemFeatureService") as mock_account_feature_service,):# Setup default mock returns for app service- mock_feature_service.get_system_features.return_value.webapp_auth.enabled = False+ mock_feature_service.is_webapp_auth_enabled.return_value = Falsemock_enterprise_service.WebAppAuth.update_app_access_mode.return_value = Nonemock_enterprise_service.WebAppAuth.cleanup_webapp.return_value = None# Setup default mock returns for account service- mock_account_feature_service.get_system_features.return_value.is_allow_register = True+ mock_account_feature_service.is_registration_allowed.return_value = True# Mock ModelManager for model configurationmock_model_instance = mock_model_manager.return_value@@ -64,9 +64,7 @@ class TestWorkflowRunService:fake = Faker()# Setup mocks for account creation- mock_external_service_dependencies[- "account_feature_service"- ].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenantaccount = AccountService.create_account(diff --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 b12472c586c..c2c5fe838fb 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@@ -23,10 +23,10 @@ class TestWorkflowToolManageService:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.app_service.FeatureService") as mock_feature_service,+ 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.FeatureService") as mock_account_feature_service,+ patch("services.account_service.SystemFeatureService") as mock_account_feature_service,patch("services.tools.workflow_tools_manage_service.WorkflowToolProviderController") as mock_workflow_tool_provider_controller,@@ -34,12 +34,12 @@ class TestWorkflowToolManageService:patch("services.tools.workflow_tools_manage_service.ToolTransformService") as mock_tool_transform_service,):# Setup default mock returns for app service- mock_feature_service.get_system_features.return_value.webapp_auth.enabled = False+ mock_feature_service.is_webapp_auth_enabled.return_value = Falsemock_enterprise_service.WebAppAuth.update_app_access_mode.return_value = Nonemock_enterprise_service.WebAppAuth.cleanup_webapp.return_value = None# Setup default mock returns for account service- mock_account_feature_service.get_system_features.return_value.is_allow_register = True+ mock_account_feature_service.is_registration_allowed.return_value = True# Mock ModelManager for model configurationmock_model_instance = mock_model_manager.return_value@@ -79,9 +79,7 @@ class TestWorkflowToolManageService:fake = Faker()# Setup mocks for account creation- mock_external_service_dependencies[- "account_feature_service"- ].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["account_feature_service"].is_registration_allowed.return_value = True# Create account and tenantaccount = AccountService.create_account(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 b8327db67f4..b2007608e42 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@@ -37,10 +37,10 @@ class TestCleanNotionDocumentTask:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.account_service.FeatureService") as mock_account_feature_service,+ patch("services.account_service.SystemFeatureService") as mock_account_feature_service,):# Setup default mock returns for account service- mock_account_feature_service.get_system_features.return_value.is_allow_register = True+ mock_account_feature_service.is_registration_allowed.return_value = Trueyield {"account_feature_service": mock_account_feature_service,diff --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 b0704ae9303..6499d251048 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@@ -29,10 +29,10 @@ class TestDealDatasetVectorIndexTask:def mock_external_service_dependencies(self):"""Mock setup for external service dependencies."""with (- patch("services.account_service.FeatureService") as mock_account_feature_service,+ patch("services.account_service.SystemFeatureService") as mock_account_feature_service,):# Setup default mock returns for account service- mock_account_feature_service.get_system_features.return_value.is_allow_register = True+ mock_account_feature_service.is_registration_allowed.return_value = Trueyield {"account_feature_service": mock_account_feature_service,diff --git a/api/tests/test_containers_integration_tests/trigger/test_trigger_e2e.py b/api/tests/test_containers_integration_tests/trigger/test_trigger_e2e.pyindex c08b0be6a04..7bc578ed6a5 100644--- a/api/tests/test_containers_integration_tests/trigger/test_trigger_e2e.py+++ b/api/tests/test_containers_integration_tests/trigger/test_trigger_e2e.py@@ -41,7 +41,7 @@ from models.trigger import (from models.workflow import Workflowfrom schedule import workflow_schedule_taskfrom schedule.workflow_schedule_task import poll_workflow_schedules-from services import feature_service as feature_service_module+from services.system_feature_service import SystemFeatureServicefrom services.trigger import webhook_servicefrom services.trigger.schedule_service import ScheduleServicefrom services.workflow_service import WorkflowService@@ -112,7 +112,7 @@ def test_publish_blocks_start_and_trigger_coexistence(workflow_service = WorkflowService()monkeypatch.setattr(- feature_service_module.FeatureService,+ SystemFeatureService,"is_plugin_manager_enabled",classmethod(lambda _cls: False),)diff --git a/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py b/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.pyindex c2b43d8cb22..f39a8e8a3c9 100644--- a/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py+++ b/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py@@ -409,9 +409,9 @@ def test_agent_app_list_and_create_use_agent_route(get_or_create_debug_conversation,)monkeypatch.setattr(- roster_controller.FeatureService,- "get_system_features",- lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ roster_controller.SystemFeatureService,+ "is_webapp_auth_enabled",+ lambda: False,)with app.test_request_context("/console/api/agent?page=1&limit=10&mode=workflow&sort_by=recently_created"@@ -565,9 +565,9 @@ def test_agent_app_detail_update_delete_resolve_app_from_agent_id(roster_controller.AgentRosterService, "count_agent_app_debug_conversation_messages", lambda _self, **kwargs: 2)monkeypatch.setattr(- roster_controller.FeatureService,- "get_system_features",- lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ roster_controller.SystemFeatureService,+ "is_webapp_auth_enabled",+ lambda: False,)monkeypatch.setattr(roster_controller,@@ -1025,9 +1025,9 @@ def test_agent_app_update_allows_empty_role(roster_controller.AgentRosterService, "count_agent_app_debug_conversation_messages", lambda _self, **kwargs: 0)monkeypatch.setattr(- roster_controller.FeatureService,- "get_system_features",- lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ roster_controller.SystemFeatureService,+ "is_webapp_auth_enabled",+ lambda: False,)class FakeAppService: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 16c2ae1007d..c2d6a756062 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@@ -13,14 +13,12 @@ from sqlalchemy import Engine, eventfrom sqlalchemy.orm import Sessionfrom controllers.console.app import app_import as app_import_module-from enums import DeploymentEditionfrom models.account import Account, Tenantfrom models.base import TypeBasefrom models.engine import dbfrom models.model import App, AppModefrom services.app_dsl_service import ImportStatusfrom services.entities.dsl_entities import CheckDependenciesResult-from services.entities.feature_entities import SystemFeatureModel, WebAppAuthModelfrom tests.unit_tests.config_override import apply_config_overrides@@ -49,11 +47,7 @@ class _Result:def _install_features(monkeypatch: pytest.MonkeyPatch, enabled: bool) -> None:- features = SystemFeatureModel(- deployment_edition=DeploymentEdition.COMMUNITY,- webapp_auth=WebAppAuthModel(enabled=enabled),- )- monkeypatch.setattr(app_import_module.FeatureService, "get_system_features", lambda: features)+ monkeypatch.setattr(app_import_module.SystemFeatureService, "is_webapp_auth_enabled", lambda: enabled)def _make_account(account_id: str = "u1") -> Account:diff --git a/api/tests/unit_tests/controllers/console/app/test_app_response_models.py b/api/tests/unit_tests/controllers/console/app/test_app_response_models.pyindex b8a5ec91f40..2c7a6ca9e90 100644--- a/api/tests/unit_tests/controllers/console/app/test_app_response_models.py+++ b/api/tests/unit_tests/controllers/console/app/test_app_response_models.py@@ -563,8 +563,8 @@ def test_app_list_uses_injected_session_for_draft_workflows()monkeypatch.setattr(app_module,- "FeatureService",- SimpleNamespace(get_system_features=lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False))),+ "SystemFeatureService",+ SimpleNamespace(is_webapp_auth_enabled=lambda: False),)get_permissions = MagicMock(return_value=app_module.enterprise_rbac_service.MyPermissionsResponse(@@ -680,9 +680,9 @@ def test_app_list_api_attaches_permission_keys(get_paginate_apps,)monkeypatch.setattr(- app_module.FeatureService,- "get_system_features",- lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ app_module.SystemFeatureService,+ "is_webapp_auth_enabled",+ lambda: False,)monkeypatch.setattr(app_module.enterprise_rbac_service.RBACService.MyPermissions,@@ -865,9 +865,9 @@ def test_app_list_api_limits_to_apps_created_by_current_user_without_view_permislambda tenant_id, account_id: SimpleNamespace(resource_ids=["app-shared", "app-not-permitted"]),)monkeypatch.setattr(- app_module.FeatureService,- "get_system_features",- lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ app_module.SystemFeatureService,+ "is_webapp_auth_enabled",+ lambda: False,)resp, status = method(app_module.AppListApi(), "tenant-1", "acct-1", unbound_session)@@ -922,9 +922,9 @@ def test_app_list_api_limits_to_preview_overrides_without_manage_own_permission(lambda tenant_id, account_id: SimpleNamespace(resource_ids=["app-whitelist-only"]),)monkeypatch.setattr(- app_module.FeatureService,- "get_system_features",- lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ app_module.SystemFeatureService,+ "is_webapp_auth_enabled",+ lambda: False,)method(app_module.AppListApi(), "tenant-1", "acct-1", unbound_session)@@ -960,9 +960,9 @@ def test_app_list_api_returns_no_apps_without_workspace_or_resource_view_permisslambda tenant_id, account_id: SimpleNamespace(resource_ids=["app-not-permitted"]),)monkeypatch.setattr(- app_module.FeatureService,- "get_system_features",- lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ app_module.SystemFeatureService,+ "is_webapp_auth_enabled",+ lambda: False,)method(app_module.AppListApi(), "tenant-1", "acct-1", unbound_session)@@ -996,9 +996,9 @@ def test_app_detail_api_attaches_current_user_permission_keys(get_app = MagicMock(return_value=app_obj)monkeypatch.setattr(app_module, "AppService", lambda: SimpleNamespace(get_app=get_app))monkeypatch.setattr(- app_module.FeatureService,- "get_system_features",- lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ app_module.SystemFeatureService,+ "is_webapp_auth_enabled",+ lambda: False,)get_permissions = MagicMock(return_value=app_module.enterprise_rbac_service.MyPermissionsResponse(@@ -1081,9 +1081,9 @@ def test_app_copy_api_attaches_permission_keys(),)monkeypatch.setattr(- app_module.FeatureService,- "get_system_features",- lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ app_module.SystemFeatureService,+ "is_webapp_auth_enabled",+ lambda: False,)monkeypatch.setattr(app_module, "db", SimpleNamespace(engine=sqlite_engine))monkeypatch.setattr(diff --git a/api/tests/unit_tests/controllers/console/auth/test_authentication_security.py b/api/tests/unit_tests/controllers/console/auth/test_authentication_security.pyindex 64e2813f62f..c5ea4d69ace 100644--- a/api/tests/unit_tests/controllers/console/auth/test_authentication_security.py+++ b/api/tests/unit_tests/controllers/console/auth/test_authentication_security.py@@ -32,7 +32,7 @@ class TestAuthenticationSecurity:self.app.config["TESTING"] = True@patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.FeatureService.get_system_features")+ @patch("controllers.console.auth.login.SystemFeatureService.is_registration_allowed")@patch("controllers.console.auth.login.AccountService.is_login_error_rate_limit")@patch("controllers.console.auth.login.AccountService.authenticate")@patch("controllers.console.auth.login.AccountService.add_login_error_rate_limit")@@ -46,7 +46,7 @@ class TestAuthenticationSecurity:mock_is_rate_limit.return_value = Falsemock_get_invitation.return_value = Nonemock_authenticate.side_effect = services.errors.account.AccountPasswordError("Invalid email or password.")- mock_features.return_value.is_allow_register = True+ mock_features.return_value = True# Actwith self.app.test_request_context(@@ -96,7 +96,7 @@ class TestAuthenticationSecurity:mock_add_rate_limit.assert_called_once_with("[email protected]")@patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.FeatureService.get_system_features")+ @patch("controllers.console.auth.login.SystemFeatureService.is_registration_allowed")@patch("controllers.console.auth.login.AccountService.is_login_error_rate_limit")@patch("controllers.console.auth.login.AccountService.authenticate")@patch("controllers.console.auth.login.AccountService.add_login_error_rate_limit")@@ -110,7 +110,7 @@ class TestAuthenticationSecurity:mock_is_rate_limit.return_value = Falsemock_get_invitation.return_value = Nonemock_authenticate.side_effect = services.errors.account.AccountPasswordError("Invalid email or password.")- mock_features.return_value.is_allow_register = False+ mock_features.return_value = False# Actwith self.app.test_request_context(@@ -129,7 +129,7 @@ class TestAuthenticationSecurity:mock_add_rate_limit.assert_called_once_with("[email protected]")@patch("controllers.console.wraps.db")- @patch("controllers.console.auth.login.FeatureService.get_system_features")+ @patch("controllers.console.auth.login.SystemFeatureService.is_registration_allowed")@patch("controllers.console.auth.login.AccountService.get_user_through_email")@patch("controllers.console.auth.login.AccountService.send_reset_password_email")def test_reset_password_with_existing_account(self, mock_send_email, mock_get_user, mock_features, mock_db):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 7b5f859877b..2189682f78a 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@@ -51,7 +51,6 @@ from services.account_errors import (InvalidEmailRegistrationTokenError,)from services.entities.account_entities import AccountEmailRegistrationVerification, AccountSessionTokens-from services.entities.feature_entities import SystemFeatureModel@pytest.fixture(autouse=True)@@ -68,14 +67,16 @@ def _request(payload: dict[str, str],) -> Generator[None, None, None]:services = SimpleNamespace(accounts=SimpleNamespace(email_registration=service))- features = SystemFeatureModel(- deployment_edition=DeploymentEdition.CLOUD,- enable_email_password_login=True,- is_allow_register=True,- )with (patch("controllers.console.auth.email_register.application_services", return_value=services),- patch("controllers.console.flask_admission.FeatureService.get_system_features", return_value=features),+ patch(+ "controllers.console.flask_admission.SystemFeatureService.is_email_password_login_enabled",+ return_value=True,+ ),+ patch(+ "controllers.console.flask_admission.SystemFeatureService.is_registration_allowed",+ return_value=True,+ ),patch("controllers.console.auth.email_register.extract_remote_ip", return_value="127.0.0.1"),app.test_request_context(path, method="POST", json=payload),):@@ -281,14 +282,18 @@ def test_invalid_password_is_sanitized_by_real_error_handler(caplog: pytest.LogCapp = Flask(__name__)app.config["TESTING"] = Trueapp.register_blueprint(console_bp)- features = SystemFeatureModel(- deployment_edition=DeploymentEdition.CLOUD,- enable_email_password_login=True,- is_allow_register=True,- )password_marker = "SecretMarker"- with patch("controllers.console.flask_admission.FeatureService.get_system_features", return_value=features):+ with (+ patch(+ "controllers.console.flask_admission.SystemFeatureService.is_email_password_login_enabled",+ return_value=True,+ ),+ patch(+ "controllers.console.flask_admission.SystemFeatureService.is_registration_allowed",+ return_value=True,+ ),+ ):response = app.test_client().post("/console/api/email-register",json={diff --git a/api/tests/unit_tests/controllers/console/auth/test_email_verification.py b/api/tests/unit_tests/controllers/console/auth/test_email_verification.pyindex 930ac17279b..aedea3033e7 100644--- a/api/tests/unit_tests/controllers/console/auth/test_email_verification.py+++ b/api/tests/unit_tests/controllers/console/auth/test_email_verification.py@@ -146,7 +146,7 @@ class TestEmailCodeLoginSendEmailApi:@patch("controllers.console.wraps.db")@patch("controllers.console.auth.login.AccountService.is_email_send_ip_limit")@patch("controllers.console.auth.login.AccountService.get_user_through_email")- @patch("controllers.console.auth.login.FeatureService.get_system_features")+ @patch("controllers.console.auth.login.SystemFeatureService.is_registration_allowed")@patch("controllers.console.auth.login.AccountService.send_email_code_login_email")def test_send_email_code_new_user_registration_allowed(self, mock_send_email, mock_get_features, mock_get_user, mock_is_ip_limit, mock_db, app@@ -161,7 +161,7 @@ class TestEmailCodeLoginSendEmailApi:# Arrangemock_is_ip_limit.return_value = Falsemock_get_user.return_value = None- mock_get_features.return_value.is_allow_register = True+ mock_get_features.return_value = Truemock_send_email.return_value = "email_token_123"# Act@@ -178,7 +178,7 @@ class TestEmailCodeLoginSendEmailApi:@patch("controllers.console.wraps.db")@patch("controllers.console.auth.login.AccountService.is_email_send_ip_limit")@patch("controllers.console.auth.login.AccountService.get_user_through_email")- @patch("controllers.console.auth.login.FeatureService.get_system_features")+ @patch("controllers.console.auth.login.SystemFeatureService.is_registration_allowed")def test_send_email_code_new_user_registration_disabled(self, mock_get_features, mock_get_user, mock_is_ip_limit, mock_db, app):@@ -192,7 +192,7 @@ class TestEmailCodeLoginSendEmailApi:# Arrangemock_is_ip_limit.return_value = Falsemock_get_user.return_value = None- mock_get_features.return_value.is_allow_register = False+ mock_get_features.return_value = False# Act & Assertwith app.test_request_context("/email-code-login", method="POST", json={"email": "[email protected]"}):@@ -766,7 +766,7 @@ class TestEmailCodeLoginApi:@patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")@patch("controllers.console.auth.login.AccountService.get_user_through_email")@patch("controllers.console.auth.login.TenantService.get_join_tenants")- @patch("controllers.console.auth.login.FeatureService.is_workspace_creation_allowed")+ @patch("controllers.console.auth.login.SystemFeatureService.is_workspace_creation_allowed")def test_email_code_login_creates_workspace_for_user_without_tenant(self,mock_is_workspace_creation_allowed,@@ -806,8 +806,8 @@ class TestEmailCodeLoginApi:@patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")@patch("controllers.console.auth.login.AccountService.get_user_through_email")@patch("controllers.console.auth.login.TenantService.get_join_tenants")- @patch("controllers.console.auth.login.FeatureService.get_license")- @patch("controllers.console.auth.login.FeatureService.is_workspace_creation_allowed")+ @patch("controllers.console.auth.login.SystemFeatureService.get_license")+ @patch("controllers.console.auth.login.SystemFeatureService.is_workspace_creation_allowed")def test_email_code_login_workspace_limit_exceeded(self,mock_is_workspace_creation_allowed,@@ -848,7 +848,7 @@ class TestEmailCodeLoginApi:@patch("controllers.console.auth.login.AccountService.verify_email_code_login_challenge")@patch("controllers.console.auth.login.AccountService.get_user_through_email")@patch("controllers.console.auth.login.TenantService.get_join_tenants")- @patch("controllers.console.auth.login.FeatureService.is_workspace_creation_allowed")+ @patch("controllers.console.auth.login.SystemFeatureService.is_workspace_creation_allowed")def test_email_code_login_workspace_creation_not_allowed(self,mock_is_workspace_creation_allowed,diff --git a/api/tests/unit_tests/controllers/console/auth/test_forgot_password.py b/api/tests/unit_tests/controllers/console/auth/test_forgot_password.pyindex b9eda4eeb0a..658cad2c35b 100644--- a/api/tests/unit_tests/controllers/console/auth/test_forgot_password.py+++ b/api/tests/unit_tests/controllers/console/auth/test_forgot_password.py@@ -59,11 +59,14 @@ class TestForgotPasswordSendEmailApi:)with (patch(- "controllers.console.auth.forgot_password.FeatureService.get_system_features",- return_value=controller_features,+ "controllers.console.auth.forgot_password.SystemFeatureService.is_registration_allowed",+ return_value=controller_features.is_allow_register,),config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD),- patch("controllers.console.wraps.FeatureService.get_system_features", return_value=wraps_features),+ patch(+ "controllers.console.wraps.SystemFeatureService.is_email_password_login_enabled",+ return_value=wraps_features.enable_email_password_login,+ ),):with app.test_request_context("/forgot-password",@@ -110,7 +113,10 @@ class TestForgotPasswordCheckApi:)with (config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD),- patch("controllers.console.wraps.FeatureService.get_system_features", return_value=wraps_features),+ patch(+ "controllers.console.wraps.SystemFeatureService.is_email_password_login_enabled",+ return_value=wraps_features.enable_email_password_login,+ ),):with app.test_request_context("/forgot-password/validity",@@ -156,7 +162,10 @@ class TestForgotPasswordResetApi:)with (config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD),- patch("controllers.console.wraps.FeatureService.get_system_features", return_value=wraps_features),+ patch(+ "controllers.console.wraps.SystemFeatureService.is_email_password_login_enabled",+ return_value=wraps_features.enable_email_password_login,+ ),):with database_app.test_request_context("/forgot-password/resets",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 bec3305387b..61a78011987 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@@ -479,8 +479,8 @@ class TestLoginApi:@patch("controllers.console.auth.login.RegisterService.get_invitation_with_case_fallback")@patch("controllers.console.auth.login.AccountService.authenticate")@patch("controllers.console.auth.login.TenantService.get_join_tenants")- @patch("controllers.console.auth.login.FeatureService.get_license")- @patch("controllers.console.auth.login.FeatureService.is_workspace_creation_allowed")+ @patch("controllers.console.auth.login.SystemFeatureService.get_license")+ @patch("controllers.console.auth.login.SystemFeatureService.is_workspace_creation_allowed")def test_login_fails_when_no_workspace_and_limit_exceeded(self,mock_is_workspace_creation_allowed: MagicMock,diff --git a/api/tests/unit_tests/controllers/console/auth/test_oauth.py b/api/tests/unit_tests/controllers/console/auth/test_oauth.pyindex 1d95860e1b4..3a0d1b24310 100644--- a/api/tests/unit_tests/controllers/console/auth/test_oauth.py+++ b/api/tests/unit_tests/controllers/console/auth/test_oauth.py@@ -534,7 +534,7 @@ class TestAccountGeneration:],)@patch("controllers.console.auth.oauth._get_account_by_openid_or_email")- @patch("controllers.console.auth.oauth.FeatureService")+ @patch("controllers.console.auth.oauth.SystemFeatureService")@patch("controllers.console.auth.oauth.RegisterService")@patch("controllers.console.auth.oauth.AccountService")@patch("controllers.console.auth.oauth.TenantService")@@ -553,7 +553,7 @@ class TestAccountGeneration:should_create,):mock_get_account.return_value = mock_account if existing_account else None- mock_feature_service.get_system_features.return_value.is_allow_register = allow_register+ mock_feature_service.is_registration_allowed.return_value = allow_registermock_register_service.register.return_value = mock_accountwith app.test_request_context(headers={"Accept-Language": "en-US,en;q=0.9"}):@@ -590,7 +590,7 @@ class TestAccountGeneration:@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)@patch("controllers.console.auth.oauth.BillingService.get_email_freeze_type")@patch("controllers.console.auth.oauth._get_account_by_openid_or_email", return_value=None)- @patch("controllers.console.auth.oauth.FeatureService")+ @patch("controllers.console.auth.oauth.SystemFeatureService")def test_should_reject_registration_for_frozen_email(self,mock_feature_service,@@ -601,7 +601,7 @@ class TestAccountGeneration:app: Flask,user_info: OAuthUserInfo,):- mock_feature_service.get_system_features.return_value.is_allow_register = False+ mock_feature_service.is_registration_allowed.return_value = Falsemock_get_freeze_type.return_value = freeze_typewith app.test_request_context("/"):@@ -611,7 +611,7 @@ class TestAccountGeneration:mock_get_freeze_type.assert_called_once_with("[email protected]")@patch("controllers.console.auth.oauth._get_account_by_openid_or_email", return_value=None)- @patch("controllers.console.auth.oauth.FeatureService")+ @patch("controllers.console.auth.oauth.SystemFeatureService")@patch("controllers.console.auth.oauth.RegisterService")@patch("controllers.console.auth.oauth.AccountService")@patch("controllers.console.auth.oauth.TenantService")@@ -625,7 +625,7 @@ class TestAccountGeneration:app: Flask,):user_info = OAuthUserInfo(id="123", name="Test User", email="[email protected]")- mock_feature_service.get_system_features.return_value.is_allow_register = True+ mock_feature_service.is_registration_allowed.return_value = Truemock_register_service.register.return_value = Account(name="Test User", email="[email protected]")with app.test_request_context(headers={"Accept-Language": "en-US"}):@@ -644,7 +644,7 @@ class TestAccountGeneration:)@patch("controllers.console.auth.oauth._get_account_by_openid_or_email", return_value=None)- @patch("controllers.console.auth.oauth.FeatureService")+ @patch("controllers.console.auth.oauth.SystemFeatureService")@patch("controllers.console.auth.oauth.RegisterService")@patch("controllers.console.auth.oauth.AccountService")@patch("controllers.console.auth.oauth.TenantService")@@ -658,7 +658,7 @@ class TestAccountGeneration:app: Flask,user_info: OAuthUserInfo,):- mock_feature_service.get_system_features.return_value.is_allow_register = True+ mock_feature_service.is_registration_allowed.return_value = Truemock_register_service.register.return_value = Account(name="Test User", email="[email protected]")with app.test_request_context(headers={"Accept-Language": "zh-Hans,zh;q=0.9"}):@@ -677,7 +677,7 @@ class TestAccountGeneration:)@patch("controllers.console.auth.oauth._get_account_by_openid_or_email", return_value=None)- @patch("controllers.console.auth.oauth.FeatureService")+ @patch("controllers.console.auth.oauth.SystemFeatureService")@patch("controllers.console.auth.oauth.RegisterService")@patch("controllers.console.auth.oauth.AccountService")@patch("controllers.console.auth.oauth.TenantService")@@ -691,7 +691,7 @@ class TestAccountGeneration:app: Flask,user_info: OAuthUserInfo,):- mock_feature_service.get_system_features.return_value.is_allow_register = True+ mock_feature_service.is_registration_allowed.return_value = Truemock_register_service.register.return_value = Account(name="Test User", email="[email protected]")with app.test_request_context(headers={"Accept-Language": "en-US,en;q=0.9"}):@@ -711,7 +711,7 @@ class TestAccountGeneration:@patch("controllers.console.auth.oauth._get_account_by_openid_or_email")@patch("controllers.console.auth.oauth.TenantService")- @patch("controllers.console.auth.oauth.FeatureService")+ @patch("controllers.console.auth.oauth.SystemFeatureService")@patch("controllers.console.auth.oauth.AccountService")def test_should_create_workspace_for_account_without_tenant(self,diff --git a/api/tests/unit_tests/controllers/console/auth/test_oauth_timezone.py b/api/tests/unit_tests/controllers/console/auth/test_oauth_timezone.pyindex 74bd9ec0be4..f4a332305cf 100644--- a/api/tests/unit_tests/controllers/console/auth/test_oauth_timezone.py+++ b/api/tests/unit_tests/controllers/console/auth/test_oauth_timezone.py@@ -42,7 +42,7 @@ def test_oauth_login_passes_language_and_timezone_to_authorization_url(@patch("controllers.console.auth.oauth.AccountService.link_account_integrate")@patch("controllers.console.auth.oauth.RegisterService")-@patch("controllers.console.auth.oauth.FeatureService")+@patch("controllers.console.auth.oauth.SystemFeatureService")@patch("controllers.console.auth.oauth._get_account_by_openid_or_email", return_value=None)def test_generate_account_registers_with_browser_timezone(mock_get_account,@@ -53,7 +53,7 @@ def test_generate_account_registers_with_browser_timezone():account = Account(name="Test User", email="[email protected]")mock_register_service.register.return_value = account- mock_feature_service.get_system_features.return_value.is_allow_register = True+ mock_feature_service.is_registration_allowed.return_value = Trueuser_info = OAuthUserInfo(id="github-123", name="Test User", email="[email protected]")with app.test_request_context(headers={"Accept-Language": "zh-Hans,zh;q=0.9"}):@@ -79,7 +79,7 @@ def test_generate_account_registers_with_browser_timezone(@patch("controllers.console.auth.oauth.AccountService.link_account_integrate")@patch("controllers.console.auth.oauth.RegisterService")-@patch("controllers.console.auth.oauth.FeatureService")+@patch("controllers.console.auth.oauth.SystemFeatureService")@patch("controllers.console.auth.oauth._get_account_by_openid_or_email", return_value=None)def test_generate_account_prefers_state_language_over_accept_language(mock_get_account,@@ -90,7 +90,7 @@ def test_generate_account_prefers_state_language_over_accept_language():account = Account(name="Test User", email="[email protected]")mock_register_service.register.return_value = account- mock_feature_service.get_system_features.return_value.is_allow_register = True+ mock_feature_service.is_registration_allowed.return_value = Trueuser_info = OAuthUserInfo(id="github-123", name="Test User", email="[email protected]")with app.test_request_context(headers={"Accept-Language": "en-US,en;q=0.9"}):@@ -111,7 +111,7 @@ def test_generate_account_prefers_state_language_over_accept_language(@patch("controllers.console.auth.oauth.RegisterService")-@patch("controllers.console.auth.oauth.FeatureService")+@patch("controllers.console.auth.oauth.SystemFeatureService")@patch("controllers.console.auth.oauth._get_account_by_openid_or_email", return_value=None)def test_generate_account_rejects_new_user_when_registration_disabled(mock_get_account,@@ -120,7 +120,7 @@ def test_generate_account_rejects_new_user_when_registration_disabled(app: Flask,config_overrides,):- mock_feature_service.get_system_features.return_value.is_allow_register = False+ mock_feature_service.is_registration_allowed.return_value = Falseconfig_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)user_info = OAuthUserInfo(id="github-123", name="Test User", email="[email protected]")diff --git a/api/tests/unit_tests/controllers/console/auth/test_password_reset.py b/api/tests/unit_tests/controllers/console/auth/test_password_reset.pyindex a94816949ac..665d5da681b 100644--- a/api/tests/unit_tests/controllers/console/auth/test_password_reset.py+++ b/api/tests/unit_tests/controllers/console/auth/test_password_reset.py@@ -49,7 +49,7 @@ def enable_password_login_wrappers(monkeypatch: pytest.MonkeyPatch) -> None:apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)monkeypatch.setattr(- "controllers.console.wraps.FeatureService.get_system_features",+ "controllers.console.wraps.SystemFeatureService.is_email_password_login_enabled",lambda: SystemFeatureModel(deployment_edition=DeploymentEdition.COMMUNITY,enable_email_password_login=True,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 002d6b61c3c..e66a461833b 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@@ -133,11 +133,14 @@ def _controller_context(role: TenantAccountRole = TenantAccountRole.OWNER,auth_enabled: bool = False,) -> Generator[None]:- features = SimpleNamespace(webapp_auth=SimpleNamespace(enabled=auth_enabled))with (patch.object(module.db, "session", database_session),patch.object(module.TenantService, "get_user_role", return_value=role),- patch.object(service_module.FeatureService, "get_system_features", return_value=features),+ patch.object(+ service_module.SystemFeatureService,+ "is_webapp_auth_enabled",+ return_value=auth_enabled,+ ),):yielddiff --git a/api/tests/unit_tests/controllers/console/explore/test_wraps.py b/api/tests/unit_tests/controllers/console/explore/test_wraps.pyindex fee341593d7..71027ae6d52 100644--- a/api/tests/unit_tests/controllers/console/explore/test_wraps.py+++ b/api/tests/unit_tests/controllers/console/explore/test_wraps.py@@ -1,4 +1,3 @@-from types import SimpleNamespacefrom unittest.mock import MagicMock, patchfrom uuid import uuid4@@ -140,16 +139,14 @@ def test_user_allowed_to_access_app_denied():def view(installed_app):return "ok"- feature = SimpleNamespace(webapp_auth=SimpleNamespace(enabled=True))-with (patch("controllers.console.explore.wraps.current_account_with_tenant",return_value=(_account(account_id="user-1"), None),),patch(- "controllers.console.explore.wraps.FeatureService.get_system_features",- return_value=feature,+ "controllers.console.explore.wraps.SystemFeatureService.is_webapp_auth_enabled",+ return_value=True,),patch("controllers.console.explore.wraps.EnterpriseService.WebAppAuth.is_user_allowed_to_access_webapp",@@ -167,16 +164,14 @@ def test_user_allowed_to_access_app_success():def view(installed_app):return "ok"- feature = SimpleNamespace(webapp_auth=SimpleNamespace(enabled=True))-with (patch("controllers.console.explore.wraps.current_account_with_tenant",return_value=(_account(account_id="user-1"), None),),patch(- "controllers.console.explore.wraps.FeatureService.get_system_features",- return_value=feature,+ "controllers.console.explore.wraps.SystemFeatureService.is_webapp_auth_enabled",+ return_value=True,),patch("controllers.console.explore.wraps.EnterpriseService.WebAppAuth.is_user_allowed_to_access_webapp",diff --git a/api/tests/unit_tests/controllers/console/test_feature.py b/api/tests/unit_tests/controllers/console/test_feature.pyindex a97f366da5b..5afc9fc1de4 100644--- a/api/tests/unit_tests/controllers/console/test_feature.py+++ b/api/tests/unit_tests/controllers/console/test_feature.py@@ -1,6 +1,6 @@from inspect import unwrapfrom types import SimpleNamespace-from unittest.mock import create_autospec+from unittest.mock import MagicMock, create_autospecfrom pytest_mock import MockerFixture@@ -27,7 +27,7 @@ def _request_context() -> RequestContext:)-def _install_application_services(mocker: MockerFixture):+def _install_application_services(mocker: MockerFixture) -> MagicMock:feature_queries = create_autospec(FeatureQueryService, instance=True, spec_set=True)services = SimpleNamespace(feature_queries=feature_queries)mocker.patch("controllers.console.feature.application_services", return_value=services)@@ -35,7 +35,7 @@ def _install_application_services(mocker: MockerFixture):class TestFeatureApi:- def test_get_tenant_features_success(self, mocker: MockerFixture):+ def test_get_tenant_features_success(self, mocker: MockerFixture) -> None:from controllers.console.feature import FeatureApifeatures = FeatureModel(@@ -59,7 +59,7 @@ class TestFeatureApi:class TestFeatureVectorSpaceApi:- def test_get_vector_space_success(self, mocker: MockerFixture):+ def test_get_vector_space_success(self, mocker: MockerFixture) -> None:from controllers.console.feature import FeatureVectorSpaceApifeature_queries = _install_application_services(mocker)@@ -75,7 +75,7 @@ class TestFeatureVectorSpaceApi:assert result == {"size": 5120, "limit": 20480}get_vector_space.assert_called_once_with(request_context)- def test_get_vector_space_preserves_unknown_usage(self, mocker: MockerFixture):+ def test_get_vector_space_preserves_unknown_usage(self, mocker: MockerFixture) -> None:from controllers.console.feature import FeatureVectorSpaceApifeature_queries = _install_application_services(mocker)@@ -88,7 +88,7 @@ class TestFeatureVectorSpaceApi:assert result == {"size": 0, "limit": 50, "usage_unknown": True}get_vector_space.assert_called_once_with(request_context)- def test_vector_space_response_schema_marks_usage_unknown_optional(self):+ def test_vector_space_response_schema_marks_usage_unknown_optional(self) -> None:schema = VectorSpaceLimitationModel.model_json_schema(mode="serialization")assert schema["required"] == ["size", "limit"]@@ -97,7 +97,7 @@ class TestFeatureVectorSpaceApi:class TestTrialModelsApi:- def test_get_trial_models_success(self, mocker: MockerFixture):+ def test_get_trial_models_success(self, mocker: MockerFixture) -> None:from controllers.console.feature import TrialModelsApifeature_queries = _install_application_services(mocker)@@ -115,7 +115,7 @@ class TestTrialModelsApi:class TestAppDslVersionApi:- def test_get_app_dsl_version_success(self, mocker: MockerFixture):+ def test_get_app_dsl_version_success(self, mocker: MockerFixture) -> None:from controllers.console.feature import AppDslVersionApifeature_queries = _install_application_services(mocker)@@ -131,7 +131,7 @@ class TestAppDslVersionApi:class TestSystemFeatureApi:- def test_get_system_features_public(self, mocker: MockerFixture):+ def test_get_system_features_public(self, mocker: MockerFixture) -> None:"""The public endpoint returns system features without any authentication input."""from controllers.console.feature import SystemFeatureApi@@ -142,7 +142,7 @@ class TestSystemFeatureApi:enable_learn_app=True,)feature_queries = _install_application_services(mocker)- get_system_features = feature_queries.get_system_features+ get_system_features = feature_queries.get_public_system_featuresget_system_features.return_value = system_featuresapi = SystemFeatureApi()@@ -158,7 +158,7 @@ class TestSystemFeatureApi:class TestSystemFeatureLicenseApi:- def test_get_license_success(self, mocker: MockerFixture):+ def test_get_license_success(self, mocker: MockerFixture) -> None:from controllers.console.feature import SystemFeatureLicenseApilicense_model = LicenseModel(diff --git a/api/tests/unit_tests/controllers/console/test_wraps.py b/api/tests/unit_tests/controllers/console/test_wraps.pyindex 20a7291ec66..aa3d966bdf7 100644--- a/api/tests/unit_tests/controllers/console/test_wraps.py+++ b/api/tests/unit_tests/controllers/console/test_wraps.py@@ -14,6 +14,7 @@ from werkzeug.exceptions import HTTPExceptionfrom controllers.common.wraps import _extract_resource_idfrom controllers.console import api as console_apifrom controllers.console import flask_admission+from controllers.console import wraps as wraps_modulefrom controllers.console.error import NotInitValidateError, NotSetupError, UnauthorizedAndForceLogoutfrom controllers.console.workspace.error import AccountNotInitializedErrorfrom controllers.console.wraps import (@@ -54,6 +55,24 @@ def reset_setup_required_cache():_is_setup_completed.reset_success()[email protected](autouse=True)+def _application_services(monkeypatch: pytest.MonkeyPatch) -> None:+ class FeatureQueries:+ @staticmethod+ def get_workspace_features(workspace_id: str):+ return wraps_module.FeatureService.get_features(workspace_id, exclude_vector_space=True)++ @staticmethod+ def get_workspace_vector_space(workspace_id: str):+ return wraps_module.FeatureService.get_vector_space(workspace_id)++ monkeypatch.setattr(+ wraps_module,+ "application_services",+ lambda: SimpleNamespace(feature_queries=FeatureQueries()),+ )++@pytest.fixture(autouse=True)def _wraps_config(config_overrides: Callable[..., None]) -> None:config_overrides(@@ -197,15 +216,18 @@ class TestCurrentContextInjection:account_initialization_required.assert_called_once()def test_console_email_registration_admission_checks_features_once(self):- features = SimpleNamespace(enable_email_password_login=True, is_allow_register=True)with (patch("controllers.console.flask_admission.setup_required", side_effect=lambda view: view) as setup_required,patch(- "controllers.console.flask_admission.FeatureService.get_system_features",- return_value=features,- ) as get_system_features,+ "controllers.console.flask_admission.SystemFeatureService.is_email_password_login_enabled",+ return_value=True,+ ) as is_email_password_login_enabled,+ patch(+ "controllers.console.flask_admission.SystemFeatureService.is_registration_allowed",+ return_value=True,+ ) as is_registration_allowed,):class Handler:@@ -218,7 +240,8 @@ class TestCurrentContextInjection:assert result == "ok"setup_required.assert_called_once()- get_system_features.assert_called_once_with()+ is_email_password_login_enabled.assert_called_once_with()+ is_registration_allowed.assert_called_once_with()@pytest.mark.parametrize(("enable_email_password_login", "is_allow_register"),@@ -232,15 +255,15 @@ class TestCurrentContextInjection:enable_email_password_login: bool,is_allow_register: bool,) -> None:- features = SimpleNamespace(- enable_email_password_login=enable_email_password_login,- is_allow_register=is_allow_register,- )with (patch("controllers.console.flask_admission.setup_required", side_effect=lambda view: view),patch(- "controllers.console.flask_admission.FeatureService.get_system_features",- return_value=features,+ "controllers.console.flask_admission.SystemFeatureService.is_email_password_login_enabled",+ return_value=enable_email_password_login,+ ),+ patch(+ "controllers.console.flask_admission.SystemFeatureService.is_registration_allowed",+ return_value=is_allow_register,),):@@ -1231,16 +1254,16 @@ class TestEnterpriseLicense:def test_should_allow_with_valid_license(self):"""Test that valid licenses allow access"""- # Arrange- mock_settings = MagicMock()- mock_settings.license.status = LicenseStatus.ACTIVE@enterprise_license_requireddef enterprise_feature():return "enterprise_success"# Act- with patch("controllers.console.wraps.FeatureService.get_system_features", return_value=mock_settings):+ with patch(+ "controllers.console.wraps.SystemFeatureService.get_license_status",+ return_value=LicenseStatus.ACTIVE,+ ):result = enterprise_feature()# Assert@@ -1249,16 +1272,16 @@ class TestEnterpriseLicense:@pytest.mark.parametrize("invalid_status", [LicenseStatus.INACTIVE, LicenseStatus.EXPIRED, LicenseStatus.LOST])def test_should_reject_with_invalid_license(self, invalid_status):"""Test that invalid licenses raise UnauthorizedAndForceLogout"""- # Arrange- mock_settings = MagicMock()- mock_settings.license.status = invalid_status@enterprise_license_requireddef enterprise_feature():return "enterprise_success"# Act & Assert- with patch("controllers.console.wraps.FeatureService.get_system_features", return_value=mock_settings):+ with patch(+ "controllers.console.wraps.SystemFeatureService.get_license_status",+ return_value=invalid_status,+ ):with pytest.raises(UnauthorizedAndForceLogout) as exc_info:enterprise_feature()assert "license is invalid" in str(exc_info.value)diff --git a/api/tests/unit_tests/controllers/console/workspace/test_members.py b/api/tests/unit_tests/controllers/console/workspace/test_members.pyindex c76d339e378..aedf0c12fc8 100644--- a/api/tests/unit_tests/controllers/console/workspace/test_members.py+++ b/api/tests/unit_tests/controllers/console/workspace/test_members.py@@ -348,7 +348,7 @@ class TestMemberInviteEmailApi: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.FeatureService.get_license",+ "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,@@ -382,7 +382,7 @@ class TestMemberInviteEmailApi: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.FeatureService.get_license",+ "controllers.console.workspace.members.SystemFeatureService.get_license",return_value=license_info,) as mock_get_license,patch(@@ -419,7 +419,7 @@ class TestMemberInviteEmailApi: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.FeatureService.get_license",+ "controllers.console.workspace.members.SystemFeatureService.get_license",return_value=license_info,) as mock_get_license,patch(@@ -455,7 +455,7 @@ class TestMemberInviteEmailApi: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.FeatureService.get_license",+ "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"),@@ -489,7 +489,7 @@ class TestMemberInviteEmailApi: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.FeatureService.get_license",+ "controllers.console.workspace.members.SystemFeatureService.get_license",return_value=license_info,),patch(diff --git a/api/tests/unit_tests/controllers/inner_api/test_auth_wraps.py b/api/tests/unit_tests/controllers/inner_api/test_auth_wraps.pyindex 38601408790..63373290f36 100644--- a/api/tests/unit_tests/controllers/inner_api/test_auth_wraps.py+++ b/api/tests/unit_tests/controllers/inner_api/test_auth_wraps.py@@ -11,7 +11,6 @@ from sqlalchemy.orm import Sessionfrom werkzeug.exceptions import HTTPExceptionfrom controllers.inner_api.wraps import (- billing_inner_api_only,enterprise_inner_api_only,enterprise_inner_api_user_auth,inner_api_only,@@ -35,68 +34,6 @@ def _stable_uuid(value: str) -> str:return str(uuid5(NAMESPACE_URL, value))-class TestBillingInnerApiOnly:- """Test billing_inner_api_only decorator"""-- def test_should_allow_when_inner_api_enabled_and_valid_key(self, app: Flask):- """Test that valid API key allows access when INNER_API is enabled"""-- # Arrange- @billing_inner_api_only- def protected_view():- return "success"-- # Act- with app.test_request_context(headers={"X-Inner-Api-Key": "valid_key"}):- result = protected_view()-- # Assert- assert result == "success"-- def test_should_return_404_when_inner_api_disabled(self, app: Flask, config_overrides):- """Test that 404 is returned when INNER_API is disabled"""-- # Arrange- @billing_inner_api_only- def protected_view():- return "success"-- # Act & Assert- config_overrides(INNER_API=False)- with app.test_request_context():- with pytest.raises(HTTPException) as exc_info:- protected_view()- assert exc_info.value.code == 404-- def test_should_return_401_when_api_key_missing(self, app: Flask):- """Test that 401 is returned when X-Inner-Api-Key header is missing"""-- # Arrange- @billing_inner_api_only- def protected_view():- return "success"-- # Act & Assert- with app.test_request_context(headers={}):- with pytest.raises(HTTPException) as exc_info:- protected_view()- assert exc_info.value.code == 401-- def test_should_return_401_when_api_key_invalid(self, app: Flask):- """Test that 401 is returned when X-Inner-Api-Key header is invalid"""-- # Arrange- @billing_inner_api_only- def protected_view():- return "success"-- # Act & Assert- with app.test_request_context(headers={"X-Inner-Api-Key": "invalid_key"}):- with pytest.raises(HTTPException) as exc_info:- protected_view()- assert exc_info.value.code == 401--class TestEnterpriseInnerApiOnly:"""Test enterprise_inner_api_only decorator"""diff --git a/api/tests/unit_tests/controllers/inner_api/test_mail.py b/api/tests/unit_tests/controllers/inner_api/test_mail.pyindex c2ca35693eb..83bf0c6c471 100644--- a/api/tests/unit_tests/controllers/inner_api/test_mail.py+++ b/api/tests/unit_tests/controllers/inner_api/test_mail.py@@ -1,206 +1,130 @@-"""-Unit tests for inner_api mail module-"""+"""Unit tests for the thin inner-mail Flask adapter and its admission boundary."""-from unittest.mock import patch+from collections.abc import Callable+from inspect import unwrap+from types import SimpleNamespace+from unittest.mock import MagicMock, patchimport pytestfrom flask import Flaskfrom pydantic import ValidationError+from werkzeug.exceptions import NotFound-from controllers.inner_api.mail import (- BaseMail,- BillingMail,- EnterpriseMail,- InnerMailPayload,-)+from controllers.inner_api.mail import BaseMail, BillingMail, EnterpriseMail, InnerMailPayload+from controllers.inner_api.wraps import InnerApiUnauthorizedError+from services.entities.mail_entities import InnerMailMessageclass TestInnerMailPayload:- """Test InnerMailPayload Pydantic model"""-- def test_valid_payload_with_all_fields(self):- """Test valid payload with all fields passes validation"""- data = {- "to": ["[email protected]"],- "subject": "Test Subject",- "body": "Test Body",- "substitutions": {"key": "value"},- }- payload = InnerMailPayload.model_validate(data)+ def test_valid_payload_with_all_fields(self) -> None:+ payload = InnerMailPayload.model_validate(+ {+ "to": ["[email protected]"],+ "subject": "Test Subject",+ "body": "Test Body",+ "substitutions": {"key": "value"},+ }+ )assert payload.to == ["[email protected]"]- assert payload.subject == "Test Subject"- assert payload.body == "Test Body"assert payload.substitutions == {"key": "value"}- def test_valid_payload_without_substitutions(self):- """Test valid payload without optional substitutions"""- data = {- "to": ["[email protected]"],- "subject": "Test Subject",- "body": "Test Body",- }- payload = InnerMailPayload.model_validate(data)- assert payload.to == ["[email protected]"]- assert payload.subject == "Test Subject"- assert payload.body == "Test Body"+ def test_valid_payload_without_substitutions(self) -> None:+ payload = InnerMailPayload.model_validate(+ {"to": ["[email protected]"], "subject": "Test Subject", "body": "Test Body"}+ )assert payload.substitutions is None- def test_empty_to_list_fails_validation(self):- """Test that empty 'to' list fails validation due to min_length=1"""- data = {- "to": [],- "subject": "Test Subject",- "body": "Test Body",- }- with pytest.raises(ValidationError):- InnerMailPayload.model_validate(data)-- def test_multiple_recipients_allowed(self):- """Test that multiple recipients are allowed"""- data = {- "to": ["[email protected]", "[email protected]"],- "subject": "Test Subject",- "body": "Test Body",- }- payload = InnerMailPayload.model_validate(data)- assert len(payload.to) == 2- assert "[email protected]" in payload.to- assert "[email protected]" in payload.to-- def test_missing_to_field_fails_validation(self):- """Test that missing 'to' field fails validation"""- data = {- "subject": "Test Subject",- "body": "Test Body",- }- with pytest.raises(ValidationError):- InnerMailPayload.model_validate(data)-- def test_missing_subject_fails_validation(self):- """Test that missing 'subject' field fails validation"""- data = {- "to": ["[email protected]"],- "body": "Test Body",- }- with pytest.raises(ValidationError):- InnerMailPayload.model_validate(data)-- def test_missing_body_fails_validation(self):- """Test that missing 'body' field fails validation"""- data = {- "to": ["[email protected]"],- "subject": "Test Subject",- }- with pytest.raises(ValidationError):- InnerMailPayload.model_validate(data)---class TestBaseMail:- """Test BaseMail API endpoint"""-- @pytest.fixture- def api_instance(self):- """Create BaseMail API instance"""- return BaseMail()-- @patch("controllers.inner_api.mail.send_inner_email_task")- def test_post_sends_email_task(self, mock_task, api_instance, app: Flask):- """Test that POST sends inner email task"""- # Arrange- mock_task.delay.return_value = None-- # Act- with app.test_request_context(- json={+ def test_valid_payload_with_null_substitutions(self) -> None:+ payload = InnerMailPayload.model_validate(+ {"to": ["[email protected]"],"subject": "Test Subject","body": "Test Body",+ "substitutions": None,}- ):- with patch("controllers.inner_api.mail.inner_api_ns") as mock_ns:- mock_ns.payload = {- "to": ["[email protected]"],- "subject": "Test Subject",- "body": "Test Body",- }- result = api_instance.post()-- # Assert- assert result == ({"message": "success"}, 200)- mock_task.delay.assert_called_once_with(- to=["[email protected]"],- subject="Test Subject",- body="Test Body",- substitutions=None,)+ assert payload.substitutions is None++ @pytest.mark.parametrize(+ "payload",+ [+ {"to": [], "subject": "Subject", "body": "Body"},+ {"subject": "Subject", "body": "Body"},+ {"to": ["[email protected]"], "body": "Body"},+ {"to": ["[email protected]"], "subject": "Subject"},+ ],+ )+ def test_invalid_payload(self, payload: dict[str, object]) -> None:+ with pytest.raises(ValidationError):+ InnerMailPayload.model_validate(payload)+- @patch("controllers.inner_api.mail.send_inner_email_task")- def test_post_with_substitutions(self, mock_task, api_instance, app: Flask):- """Test that POST sends email with substitutions"""- # Arrange- mock_task.delay.return_value = None-- # Act- with app.test_request_context():- with patch("controllers.inner_api.mail.inner_api_ns") as mock_ns:- mock_ns.payload = {- "to": ["[email protected]"],+class TestBaseMail:+ @pytest.mark.parametrize(+ ("resource_type", "payload", "expected"),+ [+ (+ EnterpriseMail,+ {"to": ["[email protected]"], "subject": "Subject", "body": "Body"},+ InnerMailMessage(recipients=("[email protected]",), subject="Subject", body="Body", substitutions=None),+ ),+ (+ BillingMail,+ {+ "to": ["[email protected]", "[email protected]"],"subject": "Hello {{name}}","body": "Welcome {{name}}!","substitutions": {"name": "John"},- }- result = api_instance.post()+ },+ InnerMailMessage(+ recipients=("[email protected]", "[email protected]"),+ subject="Hello {{name}}",+ body="Welcome {{name}}!",+ substitutions={"name": "John"},+ ),+ ),+ ],+ )+ def test_post_delegates_to_application_service(+ self,+ resource_type: type[BaseMail],+ payload: dict[str, object],+ expected: InnerMailMessage,+ app: Flask,+ ) -> None:+ mail_service = MagicMock()+ services = SimpleNamespace(inner_mail=mail_service)++ with (+ app.test_request_context(),+ patch("controllers.inner_api.mail.inner_api_ns") as namespace,+ patch("controllers.inner_api.mail.application_services", return_value=services),+ ):+ namespace.payload = payload+ result = unwrap(resource_type.post)(resource_type())- # Assertassert result == ({"message": "success"}, 200)- mock_task.delay.assert_called_once_with(- to=["[email protected]"],- subject="Hello {{name}}",- body="Welcome {{name}}!",- substitutions={"name": "John"},- )---class TestEnterpriseMail:- """Test EnterpriseMail API endpoint"""-- @pytest.fixture- def api_instance(self):- """Create EnterpriseMail API instance"""- return EnterpriseMail()-- def test_has_enterprise_inner_api_only_decorator(self, api_instance):- """Test that EnterpriseMail has enterprise_inner_api_only decorator"""- # Check method_decorators- from controllers.inner_api.wraps import enterprise_inner_api_only-- assert enterprise_inner_api_only in api_instance.method_decorators-- def test_has_setup_required_decorator(self, api_instance):- """Test that EnterpriseMail has setup_required decorator"""- # Check by decorator name instead of object reference- decorator_names = [d.__name__ for d in api_instance.method_decorators]- assert "setup_required" in decorator_names---class TestBillingMail:- """Test BillingMail API endpoint"""-- @pytest.fixture- def api_instance(self):- """Create BillingMail API instance"""- return BillingMail()-- def test_has_billing_inner_api_only_decorator(self, api_instance):- """Test that BillingMail has billing_inner_api_only decorator"""- # Check method_decorators- from controllers.inner_api.wraps import billing_inner_api_only-- assert billing_inner_api_only in api_instance.method_decorators-- def test_has_setup_required_decorator(self, api_instance):- """Test that BillingMail has setup_required decorator"""- # Check by decorator name instead of object reference- decorator_names = [d.__name__ for d in api_instance.method_decorators]- assert "setup_required" in decorator_names+ mail_service.send.assert_called_once_with(expected)+++def test_disabled_inner_api_returns_not_found_before_setup(app: Flask, config_overrides: Callable[..., None]) -> None:+ config_overrides(INNER_API=False)+ with patch(+ "controllers.console.wraps._is_setup_completed",+ side_effect=AssertionError("setup must not run before Inner API authentication"),+ ):+ with app.test_request_context(), pytest.raises(NotFound):+ EnterpriseMail().post()+++def test_invalid_inner_api_key_is_rejected_before_setup(app: Flask, config_overrides: Callable[..., None]) -> None:+ config_overrides(INNER_API=True, INNER_API_KEY="valid-key")+ with patch(+ "controllers.console.wraps._is_setup_completed",+ side_effect=AssertionError("setup must not run before Inner API authentication"),+ ):+ with (+ app.test_request_context(headers={"X-Inner-Api-Key": "invalid-key"}),+ pytest.raises(InnerApiUnauthorizedError),+ ):+ EnterpriseMail().post()diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_composition.py b/api/tests/unit_tests/controllers/openapi/auth/test_composition.pyindex e1b7a4f3cd3..a6629caabcf 100644--- a/api/tests/unit_tests/controllers/openapi/auth/test_composition.py+++ b/api/tests/unit_tests/controllers/openapi/auth/test_composition.py@@ -145,7 +145,7 @@ def _selected_webapp_steps(*, scope, app_access_mode):Patches the config-backed conditions (edition + webapp_auth) so the gatingreduces to PATH_HAS_APP_ID, LOADED_APP_IS_PRIVATE, and the request scope."""- from unittest.mock import MagicMock, patch+ from unittest.mock import patchfrom controllers.openapi.auth.data import AuthData@@ -160,12 +160,10 @@ def _selected_webapp_steps(*, scope, app_access_mode):scopes=frozenset({scope}) if scope is not None else frozenset(),app_access_mode=app_access_mode,)- features = MagicMock()- features.webapp_auth.enabled = Trueselected = []with (config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE),- patch("controllers.openapi.auth.conditions.FeatureService.get_system_features", return_value=features),+ patch("controllers.openapi.auth.conditions.SystemFeatureService.is_webapp_auth_enabled", return_value=True),):for step in account_pipeline._auth:if isinstance(step, When):diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_conditions.py b/api/tests/unit_tests/controllers/openapi/auth/test_conditions.pyindex a1f6b26c9ca..2d67cc84883 100644--- a/api/tests/unit_tests/controllers/openapi/auth/test_conditions.py+++ b/api/tests/unit_tests/controllers/openapi/auth/test_conditions.py@@ -1,4 +1,4 @@-from unittest.mock import MagicMock, patch+from unittest.mock import patchfrom controllers.openapi.auth.conditions import (EDITION_CLOUD,@@ -136,9 +136,7 @@ def test_edition_cloud():def test_webapp_auth_enabled():- mock_features = MagicMock()- mock_features.webapp_auth.enabled = True- with patch("controllers.openapi.auth.conditions.FeatureService.get_system_features", return_value=mock_features):+ with patch("controllers.openapi.auth.conditions.SystemFeatureService.is_webapp_auth_enabled", return_value=True):assert WEBAPP_AUTH_ENABLED(_ctx()) is Truediff --git a/api/tests/unit_tests/controllers/openapi/test_device_sso.py b/api/tests/unit_tests/controllers/openapi/test_device_sso.pyindex 38c5249bbc3..c59a50fb501 100644--- a/api/tests/unit_tests/controllers/openapi/test_device_sso.py+++ b/api/tests/unit_tests/controllers/openapi/test_device_sso.py@@ -1,7 +1,7 @@"""SSO-branch device-flow endpoints under /openapi/v1/oauth/device/."""import builtins-from unittest.mock import MagicMock, patch+from unittest.mock import patchimport pytestfrom flask import Flask@@ -145,12 +145,10 @@ def test_device_error_redirect_drops_malformed_user_code():def _ee_features():from services.entities.feature_entities import LicenseStatus- m = MagicMock()- m.license.status = LicenseStatus.ACTIVE- return m+ return LicenseStatus.ACTIVE-@patch("libs.device_flow_security.FeatureService.get_system_features")+@patch("libs.device_flow_security.SystemFeatureService.get_license_status")def test_sso_complete_relays_inbound_sso_error(ee_feat, openapi_app):ee_feat.return_value = _ee_features()client = openapi_app.test_client()@@ -165,7 +163,7 @@ def test_sso_complete_relays_inbound_sso_error(ee_feat, openapi_app):assert "user_code=ABCD-1234" in loc-@patch("libs.device_flow_security.FeatureService.get_system_features")+@patch("libs.device_flow_security.SystemFeatureService.get_license_status")def test_sso_complete_missing_assertion_redirects_generic(ee_feat, openapi_app):ee_feat.return_value = _ee_features()client = openapi_app.test_client()diff --git a/api/tests/unit_tests/controllers/openapi/test_oauth_sso_claims.py b/api/tests/unit_tests/controllers/openapi/test_oauth_sso_claims.pyindex 2d58c9499cc..59fdfc24d67 100644--- a/api/tests/unit_tests/controllers/openapi/test_oauth_sso_claims.py+++ b/api/tests/unit_tests/controllers/openapi/test_oauth_sso_claims.py@@ -1,6 +1,6 @@from __future__ import annotations-from unittest.mock import MagicMock, patch+from unittest.mock import patchimport pytestfrom flask import Flask@@ -19,13 +19,11 @@ def app() -> Flask:def _ee_features():from services.entities.feature_entities import LicenseStatus- m = MagicMock()- m.license.status = LicenseStatus.ACTIVE- return m+ return LicenseStatus.ACTIVE@patch("controllers.openapi.oauth_device_sso.jws")-@patch("libs.device_flow_security.FeatureService.get_system_features")+@patch("libs.device_flow_security.SystemFeatureService.get_license_status")def test_sso_complete_rejects_assertion_missing_email(ee_feat, jws_mod, app: Flask):ee_feat.return_value = _ee_features()jws_mod.verify.return_value = {"issuer": "https://idp.example", "user_code": "ABCD-EFGH", "nonce": "n"}@@ -40,7 +38,7 @@ def test_sso_complete_rejects_assertion_missing_email(ee_feat, jws_mod, app: Fla@patch("controllers.openapi.oauth_device_sso.jws")-@patch("libs.device_flow_security.FeatureService.get_system_features")+@patch("libs.device_flow_security.SystemFeatureService.get_license_status")def test_sso_complete_rejects_assertion_empty_issuer(ee_feat, jws_mod, app: Flask):ee_feat.return_value = _ee_features()jws_mod.verify.return_value = {"email": "[email protected]", "issuer": "", "user_code": "ABCD-EFGH", "nonce": "n"}diff --git a/api/tests/unit_tests/controllers/openapi/test_oauth_sso_host_header.py b/api/tests/unit_tests/controllers/openapi/test_oauth_sso_host_header.pyindex 6d0bb826ff4..2c9b1778927 100644--- a/api/tests/unit_tests/controllers/openapi/test_oauth_sso_host_header.py+++ b/api/tests/unit_tests/controllers/openapi/test_oauth_sso_host_header.py@@ -20,15 +20,13 @@ def app() -> Flask:def _ee_features():from services.entities.feature_entities import LicenseStatus- m = MagicMock()- m.license.status = LicenseStatus.ACTIVE- return m+ return LicenseStatus.ACTIVE@patch("controllers.openapi.oauth_device_sso.EnterpriseService")@patch("controllers.openapi.oauth_device_sso.jws")@patch("controllers.openapi.oauth_device_sso.DeviceFlowRedis")-@patch("libs.device_flow_security.FeatureService.get_system_features")+@patch("libs.device_flow_security.SystemFeatureService.get_license_status")@patch("libs.rate_limit.RateLimiter.is_rate_limited", new=MagicMock(return_value=False))@patch("libs.rate_limit.RateLimiter.increment_rate_limit", new=MagicMock())def test_idp_callback_url_uses_console_api_url_not_host_header(@@ -61,7 +59,7 @@ def test_idp_callback_url_uses_console_api_url_not_host_header(@patch("controllers.openapi.oauth_device_sso.DeviceFlowRedis")-@patch("libs.device_flow_security.FeatureService.get_system_features")+@patch("libs.device_flow_security.SystemFeatureService.get_license_status")@patch("libs.rate_limit.RateLimiter.is_rate_limited", new=MagicMock(return_value=False))@patch("libs.rate_limit.RateLimiter.increment_rate_limit", new=MagicMock())def test_sso_initiate_fails_closed_when_console_api_url_unset(ee_feat, redis_cls, app: Flask, config_overrides):diff --git a/api/tests/unit_tests/controllers/service_api/test_wraps.py b/api/tests/unit_tests/controllers/service_api/test_wraps.pyindex 82c03952c8d..322eac010c1 100644--- a/api/tests/unit_tests/controllers/service_api/test_wraps.py+++ b/api/tests/unit_tests/controllers/service_api/test_wraps.py@@ -12,6 +12,7 @@ from sqlalchemy import selectfrom sqlalchemy.orm import Session, scoped_sessionfrom werkzeug.exceptions import Forbidden, NotFound, ServiceUnavailable, Unauthorized+from controllers.service_api import wraps as wraps_modulefrom controllers.service_api.wraps import (DatasetApiResource,FetchUserArg,@@ -37,6 +38,20 @@ def _configure_current_app_mock(mock_current_app):mock_current_app._get_current_object = Mock(return_value=Mock())[email protected](autouse=True)+def _application_services(monkeypatch: pytest.MonkeyPatch) -> None:+ class FeatureQueries:+ @staticmethod+ def get_workspace_vector_space(workspace_id: str):+ return wraps_module.FeatureService.get_vector_space(workspace_id)++ monkeypatch.setattr(+ wraps_module,+ "application_services",+ lambda: SimpleNamespace(feature_queries=FeatureQueries()),+ )++def _session_proxy(session: Session) -> scoped_session[Session]:"""Expose the real SQLite session through Flask-SQLAlchemy's callable shape."""return scoped_session(lambda: session)diff --git a/api/tests/unit_tests/controllers/web/test_feature.py b/api/tests/unit_tests/controllers/web/test_feature.pyindex 68b8e72be71..1a08908bc25 100644--- a/api/tests/unit_tests/controllers/web/test_feature.py+++ b/api/tests/unit_tests/controllers/web/test_feature.py@@ -31,7 +31,7 @@ class TestSystemFeatureApi:) -> None:system_features = SystemFeatureModel(deployment_edition=deployment_edition)feature_queries = _install_feature_queries(mocker)- feature_queries.get_system_features.return_value = system_features+ feature_queries.get_public_system_features.return_value = system_featureswith app.test_request_context("/system-features"):result = SystemFeatureApi().get()@@ -40,7 +40,7 @@ class TestSystemFeatureApi:assert result["deployment_edition"] == deployment_edition.valueassert result["sso_enforced_for_signin_protocol"] is Noneassert result["webapp_auth"]["sso_config"]["protocol"] is None- feature_queries.get_system_features.assert_called_once_with()+ feature_queries.get_public_system_features.assert_called_once_with()def test_unauthenticated_access(self) -> None:"""SystemFeatureApi is unauthenticated by design — no WebApiResource decorator."""diff --git a/api/tests/unit_tests/controllers/web/test_passport.py b/api/tests/unit_tests/controllers/web/test_passport.pydeleted file mode 100644index 4b099deeac3..00000000000--- a/api/tests/unit_tests/controllers/web/test_passport.py+++ /dev/null@@ -1,133 +0,0 @@-from __future__ import annotations--from unittest.mock import patch-from uuid import NAMESPACE_URL, UUID, uuid5--import pytest-from sqlalchemy import select-from sqlalchemy.orm import Session-from werkzeug.exceptions import NotFound, Unauthorized--from controllers.web.error import WebAppAuthRequiredError-from controllers.web.passport import (- PassportService,- decode_enterprise_webapp_user_id,- exchange_token_for_existing_web_user,- generate_session_id,-)-from models.enums import CustomizeTokenStrategy, EndUserType-from models.model import App, AppMode, EndUser, IconType, Site-from services.webapp_auth_service import WebAppAuthType---def _stable_uuid(value: str) -> str:- return str(uuid5(NAMESPACE_URL, value))---def _persist_webapp(session: Session, *, app_code: str = "code") -> tuple[App, Site]:- tenant_id = _stable_uuid(f"tenant:{app_code}")- app_model = App(- id=_stable_uuid(f"app:{app_code}"),- tenant_id=tenant_id,- name="Web App",- mode=AppMode.CHAT,- icon_type=IconType.EMOJI,- icon="chat",- icon_background="#FFFFFF",- enable_site=True,- enable_api=False,- )- site = Site(- id=_stable_uuid(f"site:{app_code}"),- app_id=app_model.id,- title="Web App Site",- default_language="en-US",- customize_token_strategy=CustomizeTokenStrategy.UUID,- code=app_code,- )- session.add_all([app_model, site])- session.commit()- return app_model, site---def test_decode_enterprise_webapp_user_id_none() -> None:- assert decode_enterprise_webapp_user_id(None) is None---def test_decode_enterprise_webapp_user_id_invalid_source(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(PassportService, "verify", lambda *_args, **_kwargs: {"token_source": "bad"})- with pytest.raises(Unauthorized):- decode_enterprise_webapp_user_id("token")---def test_decode_enterprise_webapp_user_id_valid(monkeypatch: pytest.MonkeyPatch) -> None:- decoded = {"token_source": "webapp_login_token", "user_id": "u1"}- monkeypatch.setattr(PassportService, "verify", lambda *_args, **_kwargs: decoded)- assert decode_enterprise_webapp_user_id("token") == decoded--[email protected]("sqlite_session", [(App, Site)], indirect=True)-def test_exchange_token_public_flow(sqlite_session: Session) -> None:- app_model, site = _persist_webapp(sqlite_session)-- decoded = {"auth_type": "public"}- with (- patch("controllers.web.passport.db.session", sqlite_session),- patch("controllers.web.passport._exchange_for_public_app_token", return_value="resp") as exchange_mock,- ):- result = exchange_token_for_existing_web_user("code", decoded, WebAppAuthType.PUBLIC)-- assert result == "resp"- exchange_mock.assert_called_once_with(app_model, site, decoded)--[email protected]("sqlite_session", [(App, Site)], indirect=True)-def test_exchange_token_requires_external(sqlite_session: Session) -> None:- _persist_webapp(sqlite_session)-- decoded = {"auth_type": "internal"}- with (- patch("controllers.web.passport.db.session", sqlite_session),- pytest.raises(WebAppAuthRequiredError),- ):- exchange_token_for_existing_web_user("code", decoded, WebAppAuthType.EXTERNAL)--[email protected]("sqlite_session", [(App, Site, EndUser)], indirect=True)-def test_exchange_token_missing_session_id(sqlite_session: Session) -> None:- _persist_webapp(sqlite_session)-- decoded = {"auth_type": "internal"}- with (- patch("controllers.web.passport.db.session", sqlite_session),- pytest.raises(NotFound),- ):- exchange_token_for_existing_web_user("code", decoded, WebAppAuthType.INTERNAL)- assert sqlite_session.scalars(select(EndUser)).all() == []--[email protected]("sqlite_session", [(EndUser,)], indirect=True)-def test_generate_session_id(sqlite_session: Session) -> None:- collision_id = _stable_uuid("session:collision")- generated_id = _stable_uuid("session:generated")- sqlite_session.add(- EndUser(- id=_stable_uuid("end-user:collision"),- tenant_id=_stable_uuid("tenant:collision"),- type=EndUserType.BROWSER,- name="Existing User",- session_id=collision_id,- )- )- sqlite_session.commit()-- with (- patch("controllers.web.passport.db.session", sqlite_session),- patch(- "controllers.web.passport.uuid.uuid4",- side_effect=[UUID(collision_id), UUID(generated_id)],- ),- ):- session_id = generate_session_id()-- assert session_id == generated_iddiff --git a/api/tests/unit_tests/controllers/web/test_web_forgot_password.py b/api/tests/unit_tests/controllers/web/test_web_forgot_password.pyindex f43bf1fbf0a..5fde28d31cf 100644--- a/api/tests/unit_tests/controllers/web/test_web_forgot_password.py+++ b/api/tests/unit_tests/controllers/web/test_web_forgot_password.py@@ -41,7 +41,10 @@ def _patch_wraps():with (patch("controllers.console.wraps.db") as mock_db,config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE),- patch("controllers.console.wraps.FeatureService.get_system_features", return_value=wraps_features),+ patch(+ "controllers.console.wraps.SystemFeatureService.is_email_password_login_enabled",+ return_value=wraps_features.enable_email_password_login,+ ),):yielddiff --git a/api/tests/unit_tests/controllers/web/test_web_login.py b/api/tests/unit_tests/controllers/web/test_web_login.pyindex d0e1133fa83..54079b96c80 100644--- a/api/tests/unit_tests/controllers/web/test_web_login.py+++ b/api/tests/unit_tests/controllers/web/test_web_login.py@@ -55,7 +55,10 @@ def _patch_wraps(monkeypatch.setattr(console_wraps.db, "session", session_registry)with (patch("controllers.console.wraps.dify_config", console_dify),- patch("controllers.console.wraps.FeatureService.get_system_features", return_value=wraps_features),+ patch(+ "controllers.console.wraps.SystemFeatureService.is_email_password_login_enabled",+ return_value=wraps_features.enable_email_password_login,+ ),patch("controllers.web.login.dify_config", web_dify),):yielddiff --git a/api/tests/unit_tests/controllers/web/test_web_passport.py b/api/tests/unit_tests/controllers/web/test_web_passport.pyindex 82ec7f1bd44..9ac0b731a3a 100644--- a/api/tests/unit_tests/controllers/web/test_web_passport.py+++ b/api/tests/unit_tests/controllers/web/test_web_passport.py@@ -1,240 +1,69 @@-"""Unit tests for controllers.web.passport — token issuance and enterprise auth exchange."""+"""Unit tests for the thin web-passport Flask adapter."""-from __future__ import annotations--import uuid+from inspect import unwrapfrom types import SimpleNamespacefrom unittest.mock import MagicMock, patchimport pytestfrom flask import Flask-from sqlalchemy import Engine, select-from sqlalchemy.orm import Sessionfrom werkzeug.exceptions import NotFound, Unauthorizedfrom controllers.web.error import WebAppAuthRequiredError-from controllers.web.passport import (- PassportResource,- decode_enterprise_webapp_user_id,- exchange_token_for_existing_web_user,- generate_session_id,+from controllers.web.passport import PassportResource+from services.entities.passport_entities import WebPassportRequest, WebPassportResult+from services.web_passport_service import (+ WebPassportAuthenticationRequiredError,+ WebPassportNotFoundError,+ WebPassportUnauthorizedError,)-from models.base import TypeBase-from models.enums import CustomizeTokenStrategy, EndUserType-from models.model import App, AppMode, EndUser, IconType, Site-from services.webapp_auth_service import WebAppAuthType---def database_session(sqlite_engine: Engine):- models = (App, Site, EndUser)- tables = [model.metadata.tables[model.__tablename__] for model in models]- TypeBase.metadata.create_all(sqlite_engine, tables=tables)- with Session(sqlite_engine, expire_on_commit=False) as session:- with patch("controllers.web.passport.db.session", session):- yield session---def _persist_webapp(- session: Session,- *,- app_code: str = "code1",- enable_site: bool = True,-) -> tuple[App, Site]:- app_model = App(- id=str(uuid.uuid4()),- tenant_id=str(uuid.uuid4()),- name="Web App",- mode=AppMode.CHAT,- icon_type=IconType.EMOJI,- icon="chat",- icon_background="#FFFFFF",- enable_site=enable_site,- enable_api=False,- )- site = Site(- app_id=app_model.id,- title="Web App Site",- default_language="en-US",- customize_token_strategy=CustomizeTokenStrategy.UUID,- code=app_code,- )- session.add_all([app_model, site])- session.commit()- return app_model, site-def _end_user(app_model: App, *, session_id: str) -> EndUser:- return EndUser(- id=str(uuid.uuid4()),- tenant_id=app_model.tenant_id,- app_id=app_model.id,- type=EndUserType.BROWSER,- name="Web User",- session_id=session_id,+def test_passport_resource_parses_input_and_serializes_result(app: Flask) -> None:+ service = MagicMock()+ service.issue.return_value = WebPassportResult(access_token="issued-token")+ services = SimpleNamespace(web_passport=service)++ with (+ app.test_request_context(+ "/passport?user_id=session-1",+ headers={"X-App-Code": "app-code", "Authorization": "Bearer login-token"},+ ),+ patch("controllers.web.passport.application_services", return_value=services),+ patch("controllers.web.passport.extract_webapp_access_token", return_value="login-token"),+ ):+ result = unwrap(PassportResource.get)(PassportResource())++ assert result == {"access_token": "issued-token"}+ service.issue.assert_called_once_with(+ WebPassportRequest(app_code="app-code", user_session_id="session-1", access_token="login-token"))-# ----------------------------------------------------------------------------# decode_enterprise_webapp_user_id-# ----------------------------------------------------------------------------class TestDecodeEnterpriseWebappUserId:- def test_none_token_returns_none(self) -> None:- assert decode_enterprise_webapp_user_id(None) is None-- @patch("controllers.web.passport.PassportService")- def test_valid_token_returns_decoded(self, mock_passport_cls: MagicMock) -> None:- mock_passport_cls.return_value.verify.return_value = {- "token_source": "webapp_login_token",- "user_id": "u1",- }- result = decode_enterprise_webapp_user_id("valid-jwt")- assert result is not None- assert result["user_id"] == "u1"-- @patch("controllers.web.passport.PassportService")- def test_wrong_source_raises_unauthorized(self, mock_passport_cls: MagicMock) -> None:- mock_passport_cls.return_value.verify.return_value = {- "token_source": "other_source",- }- with pytest.raises(Unauthorized, match="Expected 'webapp_login_token'"):- decode_enterprise_webapp_user_id("bad-jwt")-- @patch("controllers.web.passport.PassportService")- def test_missing_source_raises_unauthorized(self, mock_passport_cls: MagicMock) -> None:- mock_passport_cls.return_value.verify.return_value = {}- with pytest.raises(Unauthorized, match="Expected 'webapp_login_token'"):- decode_enterprise_webapp_user_id("no-source-jwt")---# ----------------------------------------------------------------------------# generate_session_id-# ----------------------------------------------------------------------------class TestGenerateSessionId:- def test_returns_unique_session_id(self, database_session: Session) -> None:- sid = generate_session_id()- assert isinstance(sid, str)- assert len(sid) == 36 # UUID format-- def test_retries_on_collision(self, database_session: Session) -> None:- app_model, _ = _persist_webapp(database_session)- collision_id = str(uuid.uuid4())- generated_id = str(uuid.uuid4())- database_session.add(_end_user(app_model, session_id=collision_id))- database_session.commit()-- with patch(- "controllers.web.passport.uuid.uuid4",- side_effect=[uuid.UUID(collision_id), uuid.UUID(generated_id)],- ):- sid = generate_session_id()+def test_passport_resource_requires_app_code(app: Flask) -> None:+ with app.test_request_context("/passport"), pytest.raises(Unauthorized, match="X-App-Code"):+ unwrap(PassportResource.get)(PassportResource())- assert sid == generated_id--# ----------------------------------------------------------------------------# exchange_token_for_existing_web_user-# ----------------------------------------------------------------------------class TestExchangeTokenForExistingWebUser:- def test_external_auth_type_mismatch_raises(self, database_session: Session) -> None:- _persist_webapp(database_session)- decoded = {"user_id": "u1", "auth_type": "internal"} # mismatch: expected "external"- with pytest.raises(WebAppAuthRequiredError, match="external"):- exchange_token_for_existing_web_user(- app_code="code1", enterprise_user_decoded=decoded, auth_type=WebAppAuthType.EXTERNAL- )-- def test_internal_auth_type_mismatch_raises(self, database_session: Session) -> None:- _persist_webapp(database_session)- decoded = {"user_id": "u1", "auth_type": "external"} # mismatch: expected "internal"- with pytest.raises(WebAppAuthRequiredError, match="internal"):- exchange_token_for_existing_web_user(- app_code="code1", enterprise_user_decoded=decoded, auth_type=WebAppAuthType.INTERNAL- )-- def test_site_not_found_raises(self, database_session: Session) -> None:- decoded = {"user_id": "u1", "auth_type": "external"}- with pytest.raises(NotFound):- exchange_token_for_existing_web_user(- app_code="code1", enterprise_user_decoded=decoded, auth_type=WebAppAuthType.EXTERNAL- )---# ----------------------------------------------------------------------------# PassportResource.get-# ----------------------------------------------------------------------------class TestPassportResource:- @patch("controllers.web.passport.FeatureService.get_system_features")- def test_missing_app_code_raises_unauthorized(self, mock_features: MagicMock, app: Flask) -> None:- mock_features.return_value = SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False))- with app.test_request_context("/passport"):- with pytest.raises(Unauthorized, match="X-App-Code"):- PassportResource().get()-- @patch("controllers.web.passport.PassportService")- @patch("controllers.web.passport.generate_session_id", return_value="new-sess-id")- @patch("controllers.web.passport.FeatureService.get_system_features")- def test_creates_new_end_user_when_no_user_id(- self,- mock_features: MagicMock,- mock_gen_session: MagicMock,- mock_passport_cls: MagicMock,- app: Flask,- database_session: Session,- sqlite_engine: Engine,- ) -> None:- mock_features.return_value = SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False))- app_model, _ = _persist_webapp(database_session)- mock_passport_cls.return_value.issue.return_value = "issued-token"-- with app.test_request_context("/passport", headers={"X-App-Code": "code1"}):- response = PassportResource().get()-- assert response["access_token"] == "issued-token"- database_session.close()- with Session(sqlite_engine) as verification_session:- end_users = verification_session.scalars(select(EndUser)).all()- assert len(end_users) == 1- assert end_users[0].session_id == "new-sess-id"- assert end_users[0].app_id == app_model.id- assert end_users[0].tenant_id == app_model.tenant_id-- @patch("controllers.web.passport.PassportService")- @patch("controllers.web.passport.FeatureService.get_system_features")- def test_reuses_existing_end_user_when_user_id_provided(- self,- mock_features: MagicMock,- mock_passport_cls: MagicMock,- app: Flask,- database_session: Session,- ) -> None:- mock_features.return_value = SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False))- app_model, _ = _persist_webapp(database_session)- existing_user = _end_user(app_model, session_id="sess-existing")- database_session.add(existing_user)- database_session.commit()- mock_passport_cls.return_value.issue.return_value = "reused-token"-- with app.test_request_context("/passport?user_id=sess-existing", headers={"X-App-Code": "code1"}):- response = PassportResource().get()-- assert response["access_token"] == "reused-token"- end_users = database_session.scalars(select(EndUser)).all()- assert [end_user.id for end_user in end_users] == [existing_user.id]-- @patch("controllers.web.passport.FeatureService.get_system_features")- def test_site_not_found_raises(self, mock_features: MagicMock, app: Flask, database_session: Session) -> None:- mock_features.return_value = SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False))- with app.test_request_context("/passport", headers={"X-App-Code": "code1"}):- with pytest.raises(NotFound):- PassportResource().get()-- @patch("controllers.web.passport.FeatureService.get_system_features")- def test_disabled_app_raises_not_found(- self, mock_features: MagicMock, app: Flask, database_session: Session- ) -> None:- mock_features.return_value = SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False))- _persist_webapp(database_session, enable_site=False)- with app.test_request_context("/passport", headers={"X-App-Code": "code1"}):- with pytest.raises(NotFound):- PassportResource().get()+ ("service_error", "http_error"),+ [+ (WebPassportAuthenticationRequiredError("login required"), WebAppAuthRequiredError),+ (WebPassportUnauthorizedError("bad token"), Unauthorized),+ (WebPassportNotFoundError(), NotFound),+ ],+)+def test_passport_resource_translates_application_errors(+ service_error: Exception,+ http_error: type[Exception],+ app: Flask,+) -> None:+ service = MagicMock()+ service.issue.side_effect = service_error+ services = SimpleNamespace(web_passport=service)++ with (+ app.test_request_context("/passport", headers={"X-App-Code": "app-code"}),+ patch("controllers.web.passport.application_services", return_value=services),+ pytest.raises(http_error),+ ):+ unwrap(PassportResource.get)(PassportResource())diff --git a/api/tests/unit_tests/controllers/web/test_wraps.py b/api/tests/unit_tests/controllers/web/test_wraps.pyindex 10ad77f744f..b3c35d70aa3 100644--- a/api/tests/unit_tests/controllers/web/test_wraps.py+++ b/api/tests/unit_tests/controllers/web/test_wraps.py@@ -1,4 +1,3 @@-from types import SimpleNamespacefrom unittest import mockfrom uuid import uuid4@@ -90,9 +89,9 @@ def test_decode_jwt_token_uses_shared_session_factory(sqlite_session: Session) -mock.patch.object(wraps, "extract_webapp_passport", return_value="jwt-token"),mock.patch.object(wraps, "PassportService") as mock_passport_service,mock.patch.object(- wraps,- "FeatureService",- get_system_features=mock.Mock(return_value=SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False))),+ wraps.SystemFeatureService,+ "is_webapp_auth_enabled",+ return_value=False,),):mock_passport_service.return_value.verify.return_value = {diff --git a/api/tests/unit_tests/core/helper/test_credential_utils.py b/api/tests/unit_tests/core/helper/test_credential_utils.pyindex 8c32b13865a..1921ed99ae8 100644--- a/api/tests/unit_tests/core/helper/test_credential_utils.py+++ b/api/tests/unit_tests/core/helper/test_credential_utils.py@@ -50,7 +50,7 @@ def test_check_credential_policy_compliance_returns_when_feature_disabled(mocker: MockerFixture,) -> None:mocker.patch(- "services.feature_service.FeatureService.is_plugin_manager_enabled",+ "services.system_feature_service.SystemFeatureService.is_plugin_manager_enabled",return_value=False,)check_call = mocker.patch(@@ -66,7 +66,7 @@ def test_check_credential_policy_compliance_raises_when_credential_missing(mocker: MockerFixture,) -> None:mocker.patch(- "services.feature_service.FeatureService.is_plugin_manager_enabled",+ "services.system_feature_service.SystemFeatureService.is_plugin_manager_enabled",return_value=True,)mocker.patch("core.helper.credential_utils.is_credential_exists", return_value=False)@@ -79,7 +79,7 @@ def test_check_credential_policy_compliance_calls_plugin_manager_with_request(mocker: MockerFixture,) -> None:mocker.patch(- "services.feature_service.FeatureService.is_plugin_manager_enabled",+ "services.system_feature_service.SystemFeatureService.is_plugin_manager_enabled",return_value=True,)mocker.patch("core.helper.credential_utils.is_credential_exists", return_value=True)@@ -100,7 +100,7 @@ def test_check_credential_policy_compliance_skips_existence_check_when_disabled(mocker: MockerFixture,) -> None:mocker.patch(- "services.feature_service.FeatureService.is_plugin_manager_enabled",+ "services.system_feature_service.SystemFeatureService.is_plugin_manager_enabled",return_value=True,)exists_call = mocker.patch("core.helper.credential_utils.is_credential_exists")@@ -123,7 +123,7 @@ def test_check_credential_policy_compliance_returns_when_credential_id_empty(mocker: MockerFixture,) -> None:mocker.patch(- "services.feature_service.FeatureService.is_plugin_manager_enabled",+ "services.system_feature_service.SystemFeatureService.is_plugin_manager_enabled",return_value=True,)exists_call = mocker.patch("core.helper.credential_utils.is_credential_exists")diff --git a/api/tests/unit_tests/events/test_app_event_signals.py b/api/tests/unit_tests/events/test_app_event_signals.pyindex 35471eab0de..cde404407a2 100644--- a/api/tests/unit_tests/events/test_app_event_signals.py+++ b/api/tests/unit_tests/events/test_app_event_signals.py@@ -19,7 +19,7 @@ from services.app_service import AppServicedef _mock_deps() -> Iterator[None]:with (patch("services.app_service.BillingService"),- patch("services.app_service.FeatureService"),+ patch("services.app_service.SystemFeatureService"),patch("services.app_service.EnterpriseService"),patch("services.app_service.remove_app_and_related_data_task"),):diff --git a/api/tests/unit_tests/extensions/test_ext_application_services.py b/api/tests/unit_tests/extensions/test_ext_application_services.pyindex 191f13cf7e3..bcca4ab5d0f 100644--- a/api/tests/unit_tests/extensions/test_ext_application_services.py+++ b/api/tests/unit_tests/extensions/test_ext_application_services.py@@ -2,7 +2,7 @@import jsonfrom types import SimpleNamespace-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, call, patchfrom uuid import uuid4import httpx@@ -44,6 +44,7 @@ from services.billing_portal_service import BillingPortalServicefrom services.billing_service import BillingServicefrom services.compliance_download_service import ComplianceDownloadServicefrom services.enterprise.enterprise_service import WebAppSettings+from services.entities.mail_entities import InnerMailMessagefrom services.errors.enterprise import EnterpriseAPIError, EnterpriseAPINotFoundErrorfrom services.init_validation_service import InvalidInitializationPasswordErrorfrom services.partner_tenant_binding_service import PartnerTenantBindingService@@ -451,6 +452,59 @@ def test_build_application_services_wires_data_source_api_key_auth(assert isinstance(services.data_source_api_key_auth, DataSourceApiKeyAuthService)+ ("substitutions", "expected_substitutions"),+ [+ pytest.param({"name": "Ada"}, {"name": "Ada"}, id="configured"),+ pytest.param(None, {}, id="omitted-or-null"),+ ],+)+def test_build_application_services_wires_inner_mail_dispatcher(+ sqlite_session_factory: sessionmaker[Session],+ substitutions: dict[str, object] | None,+ expected_substitutions: dict[str, object],+) -> None:+ services = ext_application_services.build_application_services(+ database_client=sqlite_session_factory,+ deployment_edition=DeploymentEdition.COMMUNITY,+ initialization_password="",+ redis=MagicMock(spec=RedisClientWrapper),+ )+ message = InnerMailMessage(+ recipients=("[email protected]", "[email protected]"),+ subject="Subject",+ body="Body",+ substitutions=substitutions,+ )++ with patch("tasks.mail_inner_task.send_inner_email_task.delay") as delay:+ services.inner_mail.send(message)++ delay.assert_called_once_with(+ to=["[email protected]", "[email protected]"],+ subject="Subject",+ body="Body",+ substitutions=expected_substitutions,+ )+++def test_build_application_services_uses_passed_edition_for_webapp_auth(+ monkeypatch: pytest.MonkeyPatch,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)++ with patch("extensions.ext_application_services.DeploymentWebPassportAuthGateway") as auth_gateway:+ ext_application_services.build_application_services(+ database_client=sqlite_session_factory,+ deployment_edition=DeploymentEdition.ENTERPRISE,+ initialization_password="",+ redis=MagicMock(spec=RedisClientWrapper),+ )++ assert auth_gateway.call_args.kwargs["webapp_auth_enabled"] is True++def test_build_application_services_wires_trial_app_usage(sqlite_session_factory: sessionmaker[Session],) -> None:@@ -480,7 +534,7 @@ def test_build_application_services_adapts_enterprise_webapp_access_mode(sqlite_session_factory: sessionmaker[Session],) -> None:with (- patch("extensions.ext_application_services.FeatureService.is_webapp_auth_enabled", return_value=True),+ patch("extensions.ext_application_services.SystemFeatureService.is_webapp_auth_enabled", return_value=True),patch("extensions.ext_application_services.EnterpriseService.WebAppAuth.get_app_access_mode_by_id",return_value=SimpleNamespace(access_mode="private_all"),@@ -517,7 +571,7 @@ def test_build_application_services_maps_known_enterprise_errors(enterprise_error: Exception,) -> None:with (- patch("extensions.ext_application_services.FeatureService.is_webapp_auth_enabled", return_value=True),+ patch("extensions.ext_application_services.SystemFeatureService.is_webapp_auth_enabled", return_value=True),patch("extensions.ext_application_services.EnterpriseService.WebAppAuth.get_app_access_mode_by_id",side_effect=enterprise_error,@@ -540,7 +594,7 @@ def test_build_application_services_maps_invalid_access_mode_to_unavailable(sqlite_session_factory: sessionmaker[Session],) -> None:with (- patch("extensions.ext_application_services.FeatureService.is_webapp_auth_enabled", return_value=True),+ patch("extensions.ext_application_services.SystemFeatureService.is_webapp_auth_enabled", return_value=True),patch("extensions.ext_application_services.EnterpriseService.WebAppAuth.get_app_access_mode_by_id",return_value=SimpleNamespace(access_mode="invalid"),@@ -564,7 +618,7 @@ def test_build_application_services_does_not_hide_unknown_enterprise_errors() -> None:failure = TypeError("adapter bug")with (- patch("extensions.ext_application_services.FeatureService.is_webapp_auth_enabled", return_value=True),+ patch("extensions.ext_application_services.SystemFeatureService.is_webapp_auth_enabled", return_value=True),patch("extensions.ext_application_services.EnterpriseService.WebAppAuth.get_app_access_mode_by_id",side_effect=failure,@@ -588,7 +642,7 @@ def test_build_application_services_wires_webapp_permission() -> None:with (patch(- "extensions.ext_application_services.FeatureService.is_webapp_auth_enabled", return_value=True+ "extensions.ext_application_services.SystemFeatureService.is_webapp_auth_enabled", return_value=True) as enabled,patch("extensions.ext_application_services.EnterpriseService.WebAppAuth.get_app_access_mode_by_id",@@ -610,7 +664,12 @@ def test_build_application_services_wires_webapp_permission(assert requires_permission is Trueassert allowed is False- enabled.assert_called_once_with()+ enabled.assert_has_calls(+ [+ call(deployment_edition=DeploymentEdition.COMMUNITY),+ call(deployment_edition=DeploymentEdition.COMMUNITY),+ ]+ )get_access_mode.assert_called_once_with("app-1")is_user_allowed.assert_called_once_with("user-1", "app-1")diff --git a/api/tests/unit_tests/libs/test_workspace_permission.py b/api/tests/unit_tests/libs/test_workspace_permission.pyindex 9afbcffef9e..ca410e666ac 100644--- a/api/tests/unit_tests/libs/test_workspace_permission.py+++ b/api/tests/unit_tests/libs/test_workspace_permission.py@@ -25,18 +25,12 @@ class TestWorkspacePermissionHelper:# EnterpriseService should NOT be called in community editionmock_enterprise_service.WorkspacePermissionService.get_permission.assert_not_called()- @patch("libs.workspace_permission.FeatureService")- def test_community_edition_allows_transfer(self, mock_feature_service, config_overrides):+ def test_community_edition_allows_transfer(self, config_overrides):"""Community edition should check billing plan but not call enterprise service."""config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)- mock_features = Mock()- mock_features.is_allow_transfer_workspace = True- mock_feature_service.get_features.return_value = mock_features# Should not raise- check_workspace_owner_transfer_permission("test-workspace-id")-- mock_feature_service.get_features.assert_called_once_with("test-workspace-id", exclude_vector_space=True)+ check_workspace_owner_transfer_permission("test-workspace-id", owner_transfer_allowed=True)@patch("libs.workspace_permission.EnterpriseService")def test_enterprise_blocks_invite_when_disabled(self, mock_enterprise_service, config_overrides):@@ -67,57 +61,38 @@ class TestWorkspacePermissionHelper:mock_enterprise_service.WorkspacePermissionService.get_permission.assert_called_once_with("test-workspace-id")@patch("libs.workspace_permission.EnterpriseService")- @patch("libs.workspace_permission.FeatureService")- def test_billing_plan_blocks_transfer(self, mock_feature_service, mock_enterprise_service, config_overrides):+ def test_billing_plan_blocks_transfer(self, mock_enterprise_service, config_overrides):"""SANDBOX billing plan should block owner transfer before checking enterprise policy."""config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- mock_features = Mock()- mock_features.is_allow_transfer_workspace = False # SANDBOX plan- mock_feature_service.get_features.return_value = mock_features-with pytest.raises(Forbidden, match="Your current plan does not allow workspace ownership transfer"):- check_workspace_owner_transfer_permission("test-workspace-id")+ check_workspace_owner_transfer_permission("test-workspace-id", owner_transfer_allowed=False)# Enterprise service should NOT be called since billing plan already blocksmock_enterprise_service.WorkspacePermissionService.get_permission.assert_not_called()@patch("libs.workspace_permission.EnterpriseService")- @patch("libs.workspace_permission.FeatureService")- def test_enterprise_blocks_transfer_when_disabled(- self, mock_feature_service, mock_enterprise_service, config_overrides- ):+ def test_enterprise_blocks_transfer_when_disabled(self, mock_enterprise_service, config_overrides):"""Enterprise edition should block transfer when workspace policy is False."""config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- mock_features = Mock()- mock_features.is_allow_transfer_workspace = True # Billing plan allows- mock_feature_service.get_features.return_value = mock_features-mock_permission = Mock()mock_permission.allow_owner_transfer = False # Workspace policy blocksmock_enterprise_service.WorkspacePermissionService.get_permission.return_value = mock_permissionwith pytest.raises(Forbidden, match="Workspace policy prohibits ownership transfer"):- check_workspace_owner_transfer_permission("test-workspace-id")+ check_workspace_owner_transfer_permission("test-workspace-id", owner_transfer_allowed=True)mock_enterprise_service.WorkspacePermissionService.get_permission.assert_called_once_with("test-workspace-id")@patch("libs.workspace_permission.EnterpriseService")- @patch("libs.workspace_permission.FeatureService")- def test_enterprise_allows_transfer_when_both_enabled(- self, mock_feature_service, mock_enterprise_service, config_overrides- ):+ def test_enterprise_allows_transfer_when_both_enabled(self, mock_enterprise_service, config_overrides):"""Enterprise edition should allow transfer when both billing and workspace policy allow."""config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- mock_features = Mock()- mock_features.is_allow_transfer_workspace = True # Billing plan allows- mock_feature_service.get_features.return_value = mock_features-mock_permission = Mock()mock_permission.allow_owner_transfer = True # Workspace policy allowsmock_enterprise_service.WorkspacePermissionService.get_permission.return_value = mock_permission# Should not raise- check_workspace_owner_transfer_permission("test-workspace-id")+ check_workspace_owner_transfer_permission("test-workspace-id", owner_transfer_allowed=True)mock_enterprise_service.WorkspacePermissionService.get_permission.assert_called_once_with("test-workspace-id")diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.tomlindex 36b9a2e0605..b76a91281a7 100644--- a/api/tests/unit_tests/pyrefly.toml+++ b/api/tests/unit_tests/pyrefly.toml@@ -835,14 +835,8 @@ project-excludes = ["services/test_duplicate_document_indexing_task_proxy.py","services/test_export_app_messages.py","services/test_external_dataset_service.py",- "services/test_feature_service_app_dsl_version.py",- "services/test_feature_service_enable_app_deploy.py","services/test_feature_service_human_input_email_delivery.py",- "services/test_feature_service_learn_app.py",- "services/test_feature_service_licensed_seats.py",- "services/test_feature_service_trial_models.py","services/test_feature_service_vector_space.py",- "services/test_feature_service_webapp_public_access.py","services/test_feedback_service.py","services/test_file_service.py","services/test_human_input_delivery_test_service.py",diff --git a/api/tests/unit_tests/repositories/test_web_passport_repository.py b/api/tests/unit_tests/repositories/test_web_passport_repository.pynew file mode 100644index 00000000000..6c5a66d5528--- /dev/null+++ b/api/tests/unit_tests/repositories/test_web_passport_repository.py@@ -0,0 +1,256 @@+from collections.abc import Callable+from unittest.mock import MagicMock+from uuid import NAMESPACE_URL, uuid5++from sqlalchemy import select+from sqlalchemy.orm import Session, sessionmaker++from models.enums import CustomizeTokenStrategy, EndUserType+from models.model import App, AppMode, EndUser, IconType, Site+from repositories.web_passport_repository import WebPassportRepository+++def _stable_uuid(value: str) -> str:+ return str(uuid5(NAMESPACE_URL, value))+++def _persist_webapp(+ session: Session,+ *,+ app_code: str = "code",+ identity: str | None = None,+ enable_site: bool = True,+) -> tuple[App, Site]:+ identity = identity or app_code+ app = App(+ id=_stable_uuid(f"app:{identity}"),+ tenant_id=_stable_uuid(f"tenant:{identity}"),+ name="Web App",+ mode=AppMode.CHAT,+ icon_type=IconType.EMOJI,+ icon="chat",+ icon_background="#FFFFFF",+ enable_site=enable_site,+ enable_api=False,+ )+ site = Site(+ id=_stable_uuid(f"site:{identity}"),+ app_id=app.id,+ title="Web App Site",+ default_language="en-US",+ customize_token_strategy=CustomizeTokenStrategy.UUID,+ code=app_code,+ )+ session.add_all([app, site])+ session.commit()+ return app, site+++def _repository(+ session_factory: sessionmaker[Session],+ *,+ generate_session_id: Callable[[], str] | None = None,+) -> WebPassportRepository:+ return WebPassportRepository(+ session_factory=session_factory,+ generate_session_id=generate_session_id or (lambda: "generated-session"),+ )+++def test_get_active_web_app_returns_detached_record(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ app, site = _persist_webapp(sqlite_session)+ repository = _repository(sqlite_session_factory)++ record = repository.get_active_web_app("code")++ assert record is not None+ assert (record.site_id, record.app_id, record.tenant_id, record.app_code) == (+ site.id,+ app.id,+ app.tenant_id,+ "code",+ )+++def test_get_active_web_app_rejects_disabled_app(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ _persist_webapp(sqlite_session, enable_site=False)+ repository = _repository(sqlite_session_factory)++ assert repository.get_active_web_app("code") is None+++def test_get_active_web_app_accepts_duplicate_site_codes(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ first_app, _ = _persist_webapp(sqlite_session, app_code="duplicate", identity="first")+ second_app, _ = _persist_webapp(sqlite_session, app_code="duplicate", identity="second")+ repository = _repository(sqlite_session_factory)++ record = repository.get_active_web_app("duplicate")++ assert record is not None+ assert record.app_id in {first_app.id, second_app.id}+++def test_is_web_app_active_revalidates_site_code(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ _, site = _persist_webapp(sqlite_session)+ repository = _repository(sqlite_session_factory)+ record = repository.get_active_web_app("code")+ assert record is not None+ assert repository.is_web_app_active(record) is True++ site.code = "reset-code"+ sqlite_session.commit()++ assert repository.is_web_app_active(record) is False+++def test_resolve_standard_end_user_revalidates_app_in_transaction(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ app, _ = _persist_webapp(sqlite_session)+ repository = _repository(sqlite_session_factory)+ record = repository.get_active_web_app("code")+ assert record is not None++ app.enable_site = False+ sqlite_session.commit()++ resolution = repository.resolve_standard_end_user(record, "session")++ assert resolution.app_active is False+ assert resolution.end_user is None+ assert sqlite_session.scalar(select(EndUser).where(EndUser.session_id == "session")) is None+++def test_resolve_standard_end_user_reuses_or_creates_within_webapp(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ _persist_webapp(sqlite_session, app_code="one")+ _persist_webapp(sqlite_session, app_code="two")+ repository = _repository(sqlite_session_factory)+ app_one = repository.get_active_web_app("one")+ app_two = repository.get_active_web_app("two")+ assert app_one is not None+ assert app_two is not None++ created = repository.resolve_standard_end_user(app_one, "shared-session")+ reused = repository.resolve_standard_end_user(app_one, "shared-session")+ other_app = repository.resolve_standard_end_user(app_two, "shared-session")+ assert created.app_active is True+ assert created.end_user is not None+ assert reused.end_user == created.end_user+ assert other_app.end_user is not None+ assert other_app.end_user != created.end_user++ sqlite_session.expire_all()+ persisted = sqlite_session.scalar(select(EndUser).where(EndUser.id == created.end_user.id))+ assert persisted is not None+ assert persisted.type == EndUserType.BROWSER+ assert persisted.app_id == app_one.app_id+++def test_resolve_authenticated_end_user_prefers_session_identity(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ _persist_webapp(sqlite_session)+ repository = _repository(sqlite_session_factory)+ app = repository.get_active_web_app("code")+ assert app is not None+ existing = repository.resolve_standard_end_user(app, "existing-session")+ assert existing.end_user is not None++ resolution = repository.resolve_authenticated_end_user(+ app,+ end_user_id=existing.end_user.id,+ session_id="authenticated-session",+ )++ assert resolution.app_active is True+ assert resolution.end_user is not None+ assert resolution.end_user != existing.end_user+ persisted = sqlite_session.scalar(select(EndUser).where(EndUser.id == resolution.end_user.id))+ assert persisted is not None+ assert persisted.session_id == "authenticated-session"+++def test_resolve_authenticated_end_user_scopes_id_to_webapp(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ _persist_webapp(sqlite_session, app_code="one")+ _persist_webapp(sqlite_session, app_code="two")+ repository = _repository(sqlite_session_factory)+ app_one = repository.get_active_web_app("one")+ app_two = repository.get_active_web_app("two")+ assert app_one is not None+ assert app_two is not None+ created = repository.resolve_standard_end_user(app_one, "session")+ assert created.end_user is not None++ same_app = repository.resolve_authenticated_end_user(+ app_one,+ end_user_id=created.end_user.id,+ session_id=None,+ )+ other_app = repository.resolve_authenticated_end_user(+ app_two,+ end_user_id=created.end_user.id,+ session_id=None,+ )++ assert same_app.end_user == created.end_user+ assert other_app.app_active is True+ assert other_app.end_user is None+++def test_resolve_standard_end_user_retries_generated_session_id_collision(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ _persist_webapp(sqlite_session)+ generate_session_id = MagicMock(side_effect=["collision", "available"])+ repository = _repository(sqlite_session_factory, generate_session_id=generate_session_id)+ app = repository.get_active_web_app("code")+ assert app is not None+ repository.resolve_standard_end_user(app, "collision")++ resolution = repository.resolve_standard_end_user(app, None)++ assert resolution.end_user is not None+ assert generate_session_id.call_count == 2+ persisted = sqlite_session.scalar(select(EndUser).where(EndUser.id == resolution.end_user.id))+ assert persisted is not None+ assert persisted.session_id == "available"+++def test_resolve_standard_end_user_treats_empty_session_as_missing(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ _persist_webapp(sqlite_session)+ generate_session_id = MagicMock(return_value="generated-session")+ repository = _repository(sqlite_session_factory, generate_session_id=generate_session_id)+ app = repository.get_active_web_app("code")+ assert app is not None++ resolution = repository.resolve_standard_end_user(app, "")++ assert resolution.end_user is not None+ generate_session_id.assert_called_once_with()+ persisted = sqlite_session.scalar(select(EndUser).where(EndUser.id == resolution.end_user.id))+ assert persisted is not None+ assert persisted.session_id == "generated-session"diff --git a/api/tests/unit_tests/services/agent/test_agent_services.py b/api/tests/unit_tests/services/agent/test_agent_services.pyindex 59454af82cd..0a0ebc4ea08 100644--- a/api/tests/unit_tests/services/agent/test_agent_services.py+++ b/api/tests/unit_tests/services/agent/test_agent_services.py@@ -5089,9 +5089,9 @@ class TestAgentAppBackingAgent:)monkeypatch.setattr(service, "_next_duplicate_agent_name", lambda **_kwargs: "Iris copy")monkeypatch.setattr(- roster_service.FeatureService,- "get_system_features",- lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ roster_service.SystemFeatureService,+ "is_webapp_auth_enabled",+ lambda: False,)session.add_all([source_config, target_config, source_app, target_app])@@ -5177,8 +5177,8 @@ class TestAgentAppBackingAgent:monkeypatch.setattr(roster_service, "AppService", FakeAppService)monkeypatch.setattr(- roster_service.FeatureService,- "get_system_features",+ roster_service.SystemFeatureService,+ "is_webapp_auth_enabled",lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=True)),)monkeypatch.setattr(roster_service.EnterpriseService, "WebAppAuth", FakeWebAppAuth)@@ -5241,8 +5241,8 @@ class TestAgentAppBackingAgent:monkeypatch.setattr(roster_service, "AppService", FakeAppService)monkeypatch.setattr(- roster_service.FeatureService,- "get_system_features",+ roster_service.SystemFeatureService,+ "is_webapp_auth_enabled",lambda: SimpleNamespace(webapp_auth=SimpleNamespace(enabled=True)),)monkeypatch.setattr(roster_service.EnterpriseService, "WebAppAuth", FakeWebAppAuth)diff --git a/api/tests/unit_tests/services/plugin/conftest.py b/api/tests/unit_tests/services/plugin/conftest.pyindex 5345db65dc9..ac0d0376898 100644--- a/api/tests/unit_tests/services/plugin/conftest.py+++ b/api/tests/unit_tests/services/plugin/conftest.py@@ -13,11 +13,11 @@ def make_features(restrict_to_marketplace: bool = False,scope: PluginInstallationScope = PluginInstallationScope.ALL,) -> MagicMock:- """Create a mock FeatureService.get_system_features() result."""- features = MagicMock()- features.plugin_installation_permission.restrict_to_marketplace_only = restrict_to_marketplace- features.plugin_installation_permission.plugin_installation_scope = scope- return features+ """Create a mock plugin installation permission."""+ permission = MagicMock()+ permission.restrict_to_marketplace_only = restrict_to_marketplace+ permission.plugin_installation_scope = scope+ return permission@pytest.fixture@@ -30,10 +30,10 @@ def mock_installer(monkeypatch: pytest.MonkeyPatch):@pytest.fixturedef mock_features():- """Patch FeatureService to return permissive defaults."""+ """Patch SystemFeatureService to return permissive defaults."""from unittest.mock import patchfeatures = make_features()- with patch("core.plugin.plugin_service.FeatureService") as mock_fs:- mock_fs.get_system_features.return_value = features+ with patch("core.plugin.plugin_service.SystemFeatureService") as mock_fs:+ mock_fs.get_plugin_installation_permission.return_value = featuresyield featuresdiff --git a/api/tests/unit_tests/services/plugin/test_plugin_service.py b/api/tests/unit_tests/services/plugin/test_plugin_service.pyindex 11865f67f7c..cf39f9ecc02 100644--- a/api/tests/unit_tests/services/plugin/test_plugin_service.py+++ b/api/tests/unit_tests/services/plugin/test_plugin_service.py@@ -1206,7 +1206,7 @@ class TestPluginModelProviderCacheInvalidation:def test_upgrade_plugin_with_marketplace_invalidates_model_provider_cache_for_tenant(self) -> None:"""Marketplace upgrades invalidate only the mutated tenant provider cache."""with (- patch(f"{MODULE}.FeatureService") as feature_service,+ patch(f"{MODULE}.SystemFeatureService") as feature_service,patch(f"{MODULE}.PluginInstaller") as installer_cls,patch(f"{MODULE}.marketplace") as marketplace,patch(f"{MODULE}.PluginService.invalidate_plugin_model_providers_cache") as invalidate_cache,@@ -1314,13 +1314,13 @@ class TestPluginModelProviderCacheInvalidation:def test_install_from_marketplace_pkg_invalidates_model_provider_cache_for_tenant(self) -> None:"""Marketplace package installs invalidate only the mutated tenant provider cache."""with (- patch(f"{MODULE}.FeatureService") as feature_service,+ patch(f"{MODULE}.SystemFeatureService") as feature_service,patch(f"{MODULE}.PluginService._check_plugin_installation_scope"),patch(f"{MODULE}.PluginInstaller") as installer_cls,patch(f"{MODULE}.PluginService.invalidate_plugin_model_providers_cache") as invalidate_cache,):- feature_service.get_system_features.return_value = SimpleNamespace(- plugin_installation_permission=SimpleNamespace(restrict_to_marketplace_only=False)+ feature_service.get_plugin_installation_permission.return_value = SimpleNamespace(+ plugin_installation_scope=PluginInstallationScope.ALL, restrict_to_marketplace_only=False)installer = installer_cls.return_valueinstaller.fetch_plugin_manifest.return_value = MagicMock()diff --git a/api/tests/unit_tests/services/plugin/test_plugin_service_installation.py b/api/tests/unit_tests/services/plugin/test_plugin_service_installation.pyindex c002b4f2983..2e1d89378c3 100644--- a/api/tests/unit_tests/services/plugin/test_plugin_service_installation.py+++ b/api/tests/unit_tests/services/plugin/test_plugin_service_installation.py@@ -123,20 +123,20 @@ class TestFetchLatestPluginVersion:class TestCheckMarketplaceOnlyPermission:- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")def test_raises_when_restricted(self, mock_fs):mock_fs.get_plugin_installation_permission.return_value = _make_permission(restrict_to_marketplace=True)with pytest.raises(PluginInstallationForbiddenError):PluginService._check_marketplace_only_permission()- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")def test_passes_when_not_restricted(self, mock_fs):mock_fs.get_plugin_installation_permission.return_value = _make_permission(restrict_to_marketplace=False)PluginService._check_marketplace_only_permission() # should not raise- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")def test_raises_when_scope_denies_all(self, mock_fs):mock_fs.get_plugin_installation_permission.return_value = _make_permission(scope=PluginInstallationScope.NONE)@@ -145,7 +145,7 @@ class TestCheckMarketplaceOnlyPermission:class TestCheckPluginInstallationScope:- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")def test_official_only_allows_langgenius(self, mock_fs):mock_fs.get_plugin_installation_permission.return_value = _make_permission(scope=PluginInstallationScope.OFFICIAL_ONLY@@ -155,7 +155,7 @@ class TestCheckPluginInstallationScope:PluginService._check_plugin_installation_scope(verification) # should not raise- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")def test_official_only_rejects_third_party(self, mock_fs):mock_fs.get_plugin_installation_permission.return_value = _make_permission(scope=PluginInstallationScope.OFFICIAL_ONLY@@ -164,7 +164,7 @@ class TestCheckPluginInstallationScope:with pytest.raises(PluginInstallationForbiddenError):PluginService._check_plugin_installation_scope(None)- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")def test_official_and_partners_allows_partner(self, mock_fs):mock_fs.get_plugin_installation_permission.return_value = _make_permission(scope=PluginInstallationScope.OFFICIAL_AND_SPECIFIC_PARTNERS@@ -174,7 +174,7 @@ class TestCheckPluginInstallationScope:PluginService._check_plugin_installation_scope(verification) # should not raise- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")def test_official_and_partners_rejects_none(self, mock_fs):mock_fs.get_plugin_installation_permission.return_value = _make_permission(scope=PluginInstallationScope.OFFICIAL_AND_SPECIFIC_PARTNERS@@ -183,7 +183,7 @@ class TestCheckPluginInstallationScope:with pytest.raises(PluginInstallationForbiddenError):PluginService._check_plugin_installation_scope(None)- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")def test_none_scope_always_raises(self, mock_fs):mock_fs.get_plugin_installation_permission.return_value = _make_permission(scope=PluginInstallationScope.NONE)verification = MagicMock()@@ -192,13 +192,13 @@ class TestCheckPluginInstallationScope:with pytest.raises(PluginInstallationForbiddenError):PluginService._check_plugin_installation_scope(verification)- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")def test_all_scope_passes_any(self, mock_fs):mock_fs.get_plugin_installation_permission.return_value = _make_permission(scope=PluginInstallationScope.ALL)PluginService._check_plugin_installation_scope(None) # should not raise- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")def test_unknown_scope_always_raises(self, mock_fs):permission = _make_permission()permission.plugin_installation_scope = cast(PluginInstallationScope, "unknown-scope")@@ -262,7 +262,7 @@ class TestUpgradePluginWithMarketplace:PluginService.upgrade_plugin_with_marketplace("t1", "same-uid", "same-uid")@patch("core.plugin.plugin_service.marketplace")- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")@patch("core.plugin.plugin_service.PluginInstaller")def test_skips_download_when_already_installed(self, mock_installer_cls, mock_fs, mock_marketplace):mock_fs.get_plugin_installation_permission.return_value = _make_permission()@@ -276,7 +276,7 @@ class TestUpgradePluginWithMarketplace:installer.upgrade_plugin.assert_called_once()@patch("core.plugin.plugin_service.download_plugin_pkg")- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")@patch("core.plugin.plugin_service.PluginInstaller")def test_downloads_when_not_installed(self, mock_installer_cls, mock_fs, mock_download):mock_fs.get_plugin_installation_permission.return_value = _make_permission()@@ -299,7 +299,7 @@ class TestUpgradePluginWithMarketplace:)@patch("core.plugin.plugin_service.download_plugin_pkg")@patch("core.plugin.plugin_service.marketplace")- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")@patch("core.plugin.plugin_service.PluginInstaller")def test_rejects_cached_pkg_outside_scope(self, mock_installer_cls, mock_fs, mock_marketplace, mock_download, scope@@ -320,7 +320,7 @@ class TestUpgradePluginWithMarketplace:mock_download.assert_not_called()installer.upload_pkg.assert_not_called()- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")@patch("core.plugin.plugin_service.PluginInstaller")def test_rejects_before_touching_daemon_when_scope_is_none(self, mock_installer_cls, mock_fs):mock_fs.get_plugin_installation_permission.return_value = _make_permission(scope=PluginInstallationScope.NONE)@@ -333,7 +333,7 @@ class TestUpgradePluginWithMarketplace:installer.upgrade_plugin.assert_not_called()@patch("core.plugin.plugin_service.marketplace")- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")@patch("core.plugin.plugin_service.PluginInstaller")def test_allows_cached_official_pkg_under_official_only(self, mock_installer_cls, mock_fs, mock_marketplace):mock_fs.get_plugin_installation_permission.return_value = _make_permission(@@ -352,7 +352,7 @@ class TestUpgradePluginWithMarketplace:class TestUpgradePluginWithGithub:- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")@patch("core.plugin.plugin_service.PluginInstaller")def test_checks_marketplace_permission_and_delegates(self, mock_installer_cls: MagicMock, mock_fs: MagicMock):mock_fs.get_plugin_installation_permission.return_value = _make_permission()@@ -367,7 +367,7 @@ class TestUpgradePluginWithGithub:class TestUploadPkg:- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")@patch("core.plugin.plugin_service.PluginInstaller")def test_runs_permission_and_scope_checks(self, mock_installer_cls: MagicMock, mock_fs: MagicMock):mock_fs.get_plugin_installation_permission.return_value = _make_permission()@@ -388,7 +388,7 @@ class TestInstallFromMarketplacePkg:PluginService.install_from_marketplace_pkg("t1", ["uid-1"])@patch("core.plugin.plugin_service.download_plugin_pkg")- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")@patch("core.plugin.plugin_service.PluginInstaller")def test_downloads_when_not_cached(self, mock_installer_cls, mock_fs, mock_download):mock_fs.get_plugin_installation_permission.return_value = _make_permission()@@ -408,7 +408,7 @@ class TestInstallFromMarketplacePkg:call_args = installer.install_from_identifiers.call_args[0]assert call_args[1] == ["resolved-uid"]- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")@patch("core.plugin.plugin_service.PluginInstaller")def test_uses_cached_when_already_downloaded(self, mock_installer_cls: MagicMock, mock_fs: MagicMock):mock_fs.get_plugin_installation_permission.return_value = _make_permission()@@ -426,7 +426,7 @@ class TestInstallFromMarketplacePkg:assert call_args[1] == ["uid-1"]@patch("core.plugin.plugin_service.download_plugin_pkg")- @patch("core.plugin.plugin_service.FeatureService")+ @patch("core.plugin.plugin_service.SystemFeatureService")@patch("core.plugin.plugin_service.PluginInstaller")def test_rejects_cached_pkg_outside_scope(self, mock_installer_cls, mock_fs, mock_download):mock_fs.get_plugin_installation_permission.return_value = _make_permission(diff --git a/api/tests/unit_tests/services/test_account_service.py b/api/tests/unit_tests/services/test_account_service.pyindex a17d285a7f9..8614264708c 100644--- a/api/tests/unit_tests/services/test_account_service.py+++ b/api/tests/unit_tests/services/test_account_service.py@@ -117,7 +117,7 @@ class TestAccountService:def mock_external_service_dependencies(self) -> Iterator[_MockDependencies]:"""Mock setup for external service dependencies."""with (- patch("services.account_service.FeatureService") as mock_feature_service,+ 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,):@@ -244,7 +244,7 @@ class TestAccountService:) -> None:"""Test successful account creation with all required parameters."""# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsemock_password_dependencies["hash_password"].return_value = b"hashed_password"@@ -289,7 +289,7 @@ class TestAccountService:sqlite_session: Session,mock_external_service_dependencies: _MockDependencies,) -> None:- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsesqlite_session.add(@@ -325,7 +325,7 @@ class TestAccountService:mock_external_service_dependencies: _MockDependencies,) -> None:"""Test account creation prefers explicit browser timezone."""- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsemock_password_dependencies["hash_password"].return_value = b"hashed_password"@@ -353,7 +353,7 @@ class TestAccountService:from controllers.console.error import AccountNotFound# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = False+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = False# Execute test and verify exceptionwith pytest.raises(AccountNotFound):@@ -372,7 +372,7 @@ class TestAccountService:) -> None:"""Test account creation with frozen email address."""# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Trueconfig_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)with pytest.raises(AccountRegisterError):@@ -386,7 +386,7 @@ class TestAccountService:def test_create_account_suspended_email_domain(self, unbound_session: Session, mock_external_service_dependencies: _MockDependencies) -> None:- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Truemock_external_service_dependencies["billing_service"@@ -434,7 +434,7 @@ class TestAccountService:) -> None:"""Test account creation without password (for invite-based registration)."""# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Execute test@@ -475,7 +475,7 @@ class TestAccountService:sqlite_session_factory: sessionmaker[Session],mock_external_service_dependencies: _MockDependencies,) -> None:- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsewith sqlite_session_factory() as service_session:@@ -771,7 +771,7 @@ class TestTenantService:def mock_external_service_dependencies(self) -> Iterator[_MockDependencies]:"""Mock setup for external service dependencies."""with (- patch("services.account_service.FeatureService") as mock_feature_service,+ patch("services.account_service.SystemFeatureService") as mock_feature_service,patch("services.account_service.BillingService") as mock_billing_service,):yield {@@ -1674,7 +1674,7 @@ class TestRegisterService:def mock_external_service_dependencies(self) -> Iterator[_MockDependencies]:"""Mock setup for external service dependencies."""with (- patch("services.account_service.FeatureService") as mock_feature_service,+ 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,):@@ -1699,7 +1699,7 @@ class TestRegisterService:) -> None:"""Test successful system setup."""# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Mock AccountService.create_account@@ -1750,7 +1750,7 @@ class TestRegisterService:sqlite_session_factory: sessionmaker[Session],mock_external_service_dependencies: _MockDependencies,) -> None:- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsemock_account = TestAccountAssociatedDataFactory.create_account_mock()@@ -1780,7 +1780,7 @@ class TestRegisterService:sqlite_session_factory: sessionmaker[Session],mock_external_service_dependencies: _MockDependencies,) -> None:- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["feature_service"].get_license.return_value.seats.is_available.return_value = True@@ -1816,7 +1816,7 @@ class TestRegisterService:"""Enterprise-only side effect should be invoked for the ENTERPRISE edition."""config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsemock_account = TestAccountAssociatedDataFactory.create_account_mock(@@ -1860,7 +1860,7 @@ class TestRegisterService:) -> None:"""Enterprise-only side effect should not be invoked for the COMMUNITY edition."""- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsemock_account = TestAccountAssociatedDataFactory.create_account_mock(@@ -1895,7 +1895,7 @@ class TestRegisterService:from services.errors.workspace import WorkSpaceNotAllowedCreateErrorconfig_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsemock_account = TestAccountAssociatedDataFactory.create_account_mock(@@ -1926,7 +1926,7 @@ class TestRegisterService:) -> None:"""Test successful account registration."""# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = Truemock_external_service_dependencies["feature_service"@@ -1973,7 +1973,7 @@ class TestRegisterService:sqlite_session: Session,mock_external_service_dependencies: _MockDependencies,) -> None:- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truesqlite_session.add(Account(name="Existing User",@@ -2001,7 +2001,7 @@ class TestRegisterService:"""Enterprise-only side effect should be invoked after successful register commit."""config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsemock_account = TestAccountAssociatedDataFactory.create_account_mock(@@ -2033,7 +2033,7 @@ class TestRegisterService:) -> None:"""Enterprise-only side effect should not be invoked for the COMMUNITY edition."""- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = Falsemock_account = TestAccountAssociatedDataFactory.create_account_mock(@@ -2067,7 +2067,7 @@ class TestRegisterService:from services.errors.workspace import WorkSpaceNotAllowedCreateErrorconfig_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = Truemock_external_service_dependencies["feature_service"@@ -2107,7 +2107,7 @@ class TestRegisterService:from services.errors.workspace import WorkspacesLimitExceededErrorconfig_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = Truemock_external_service_dependencies["feature_service"@@ -2142,7 +2142,7 @@ class TestRegisterService:) -> None:"""Test account registration with OAuth integration."""# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = Truemock_external_service_dependencies["feature_service"@@ -2195,7 +2195,7 @@ class TestRegisterService:) -> None:"""Test account registration with pending status."""# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = Truemock_external_service_dependencies["feature_service"@@ -2246,7 +2246,7 @@ class TestRegisterService:) -> None:"""Test registration when workspace creation is not allowed."""# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["feature_service"].is_workspace_creation_allowed.return_value = Truemock_external_service_dependencies["feature_service"@@ -2280,7 +2280,7 @@ class TestRegisterService:) -> None:"""Test registration with general exception handling."""# Setup mocks- mock_external_service_dependencies["feature_service"].get_system_features.return_value.is_allow_register = True+ mock_external_service_dependencies["feature_service"].is_registration_allowed.return_value = Truemock_external_service_dependencies["billing_service"].is_email_in_freeze.return_value = False# Mock AccountService.create_account to raise exceptiondiff --git a/api/tests/unit_tests/services/test_app_service.py b/api/tests/unit_tests/services/test_app_service.pyindex b9bf28be032..a2dadd3a04c 100644--- a/api/tests/unit_tests/services/test_app_service.py+++ b/api/tests/unit_tests/services/test_app_service.py@@ -132,8 +132,8 @@ class TestCreateAppTransactionBoundary:side_effect=lambda *_args: phase_events.append("external"),),patch(- "services.app_service.FeatureService.get_system_features",- return_value=SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ "services.app_service.SystemFeatureService.is_webapp_auth_enabled",+ return_value=False,),):app = AppService().create_app(@@ -197,8 +197,8 @@ class TestCreateAppTransactionBoundary:patch("services.app_service.app_was_created.send"),patch("services.app_service.enterprise_rbac_service.try_sync_creator_access_policy_member_bindings"),patch(- "services.app_service.FeatureService.get_system_features",- return_value=SimpleNamespace(webapp_auth=SimpleNamespace(enabled=False)),+ "services.app_service.SystemFeatureService.is_webapp_auth_enabled",+ return_value=False,),):app = AppService().create_app(@@ -762,7 +762,7 @@ class TestAgentAppType:patch("services.app_service.app_was_deleted.send"),patch("services.app_service.BillingService"),patch("services.app_service.EnterpriseService"),- patch("services.app_service.FeatureService"),+ patch("services.app_service.SystemFeatureService"),patch("services.app_service.remove_app_and_related_data_task.delay",side_effect=lambda **_kwargs: events.append("enqueue-app-cleanup"),@@ -913,7 +913,7 @@ class TestAgentAppType:with (patch("services.app_service.current_user", _account_identity(str(uuid4()))),patch("services.app_service.app_was_deleted.send"),- patch("services.app_service.FeatureService"),+ patch("services.app_service.SystemFeatureService"),patch("services.app_service.BillingService"),patch("services.app_service.EnterpriseService"),patch("services.app_service.AgentWorkspaceService.retire_all_for_app", return_value=[]),diff --git a/api/tests/unit_tests/services/test_feature_query_service.py b/api/tests/unit_tests/services/test_feature_query_service.pyindex 9e99acd1c1f..d39e93cb006 100644--- a/api/tests/unit_tests/services/test_feature_query_service.py+++ b/api/tests/unit_tests/services/test_feature_query_service.py@@ -52,10 +52,24 @@ def test_deployment_queries_delegate_without_request_context() -> None:)assert service.get_app_dsl_version() == "0.6.0"- assert service.get_system_features() is system_features+ assert service.get_public_system_features() is system_featuresassert service.get_license() is license_model+def test_workspace_id_queries_delegate_without_request_context() -> None:+ gateway = create_autospec(FeatureQueryGateway, instance=True, spec_set=True)+ features = FeatureModel()+ vector_space = VectorSpaceLimitationModel(size=2, limit=10)+ gateway.get_workspace_features.return_value = features+ gateway.get_vector_space.return_value = vector_space+ service = FeatureQueryService(features=gateway, app_dsl_version="0.7.0")++ assert service.get_workspace_features("workspace_123") is features+ assert service.get_workspace_vector_space("workspace_123") is vector_space+ gateway.get_workspace_features.assert_called_once_with("workspace_123")+ gateway.get_vector_space.assert_called_once_with("workspace_123")++def test_workspace_queries_require_active_workspace() -> None:gateway = create_autospec(FeatureQueryGateway, instance=True, spec_set=True)service = FeatureQueryService(features=gateway, app_dsl_version="0.7.0")diff --git a/api/tests/unit_tests/services/test_feature_service_app_dsl_version.py b/api/tests/unit_tests/services/test_feature_service_app_dsl_version.pydeleted file mode 100644index 9aa5301fbb0..00000000000--- a/api/tests/unit_tests/services/test_feature_service_app_dsl_version.py+++ /dev/null@@ -1,7 +0,0 @@-from services.feature_service import FeatureService---def test_get_system_features_excludes_app_dsl_version():- result = FeatureService.get_system_features().model_dump()-- assert "app_dsl_version" not in resultdiff --git a/api/tests/unit_tests/services/test_feature_service_change_email.py b/api/tests/unit_tests/services/test_feature_service_change_email.pydeleted file mode 100644index 9731d932ac6..00000000000--- a/api/tests/unit_tests/services/test_feature_service_change_email.py+++ /dev/null@@ -1,17 +0,0 @@-from collections.abc import Callable--import pytest--from services.feature_service import FeatureService--[email protected]("enabled", [False, True])-def test_get_system_features_reads_enable_change_email(- config_overrides: Callable[..., None],- enabled: bool,-) -> None:- config_overrides(ENABLE_CHANGE_EMAIL=enabled)-- result = FeatureService.get_system_features()-- assert result.enable_change_email is enableddiff --git a/api/tests/unit_tests/services/test_feature_service_gateway.py b/api/tests/unit_tests/services/test_feature_service_gateway.pyindex 8dd981e11f8..c4f8a2efcfd 100644--- a/api/tests/unit_tests/services/test_feature_service_gateway.py+++ b/api/tests/unit_tests/services/test_feature_service_gateway.py@@ -4,11 +4,16 @@ from enums import DeploymentEditionfrom services.entities.feature_entities import FeatureModel, SystemFeatureModelfrom services.feature_service import FeatureServicefrom services.feature_service_gateway import FeatureServiceGateway+from services.system_feature_service import SystemFeatureServicedef test_public_system_features_delegate_to_existing_service(mocker: MockerFixture) -> None:system_features = SystemFeatureModel(deployment_edition=DeploymentEdition.COMMUNITY)- get_system_features = mocker.patch.object(FeatureService, "get_system_features", return_value=system_features)+ get_system_features = mocker.patch.object(+ SystemFeatureService,+ "get_public_system_features",+ return_value=system_features,+ )result = FeatureServiceGateway().get_public_system_features()diff --git a/api/tests/unit_tests/services/test_feature_service_internal_policies.py b/api/tests/unit_tests/services/test_feature_service_internal_policies.pydeleted file mode 100644index 8fe271c609c..00000000000--- a/api/tests/unit_tests/services/test_feature_service_internal_policies.py+++ /dev/null@@ -1,48 +0,0 @@-from collections.abc import Callable--import pytest--from enums import DeploymentEdition-from services.feature_service import FeatureService---def test_workspace_creation_uses_environment_policy(- monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]-) -> None:- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY, ALLOW_CREATE_WORKSPACE=True)- monkeypatch.setattr(- "services.feature_service.EnterpriseService.get_info",- lambda: (_ for _ in ()).throw(AssertionError("enterprise API should not be called")),- )-- assert FeatureService.is_workspace_creation_allowed() is True---def test_workspace_creation_uses_enterprise_policy(- monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]-) -> None:- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- monkeypatch.setattr(- "services.feature_service.EnterpriseService.get_info",- lambda: {"IsAllowCreateWorkspace": False},- )-- assert FeatureService.is_workspace_creation_allowed() is False---def test_workspace_creation_keeps_environment_policy_when_enterprise_value_is_missing(- monkeypatch: pytest.MonkeyPatch,- config_overrides: Callable[..., None],-) -> None:- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE, ALLOW_CREATE_WORKSPACE=True)- monkeypatch.setattr("services.feature_service.EnterpriseService.get_info", lambda: {})-- assert FeatureService.is_workspace_creation_allowed() is True---def test_plugin_manager_is_enabled_only_for_enterprise(config_overrides: Callable[..., None]) -> None:- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- assert FeatureService.is_plugin_manager_enabled() is True-- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)- assert FeatureService.is_plugin_manager_enabled() is Falsediff --git a/api/tests/unit_tests/services/test_feature_service_trial_models.py b/api/tests/unit_tests/services/test_feature_service_trial_models.pyindex c4c70b80ca0..1d2ecdcaa91 100644--- a/api/tests/unit_tests/services/test_feature_service_trial_models.py+++ b/api/tests/unit_tests/services/test_feature_service_trial_models.py@@ -6,18 +6,19 @@ import pytestfrom enums import CloudPlan, DeploymentEdition, HostedTrialProviderfrom services import feature_service as feature_service_modulefrom services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureService-def test_get_system_features_excludes_trial_models():- result = FeatureService.get_system_features().model_dump()+def test_get_public_system_features_excludes_trial_models() -> None:+ result = SystemFeatureService.get_public_system_features().model_dump()assert "trial_models" not in resultdef test_get_trial_models_returns_providers_with_paid_or_trial_enabled(config_overrides: Callable[..., None],-):- values: dict[str, bool] = {}+) -> None:+ values: dict[str, object] = {}for provider in HostedTrialProvider:values[f"HOSTED_{provider.config_key}_PAID_ENABLED"] = Falsevalues[f"HOSTED_{provider.config_key}_TRIAL_ENABLED"] = Falsediff --git a/api/tests/unit_tests/services/test_inner_mail_service.py b/api/tests/unit_tests/services/test_inner_mail_service.pynew file mode 100644index 00000000000..77d861655a3--- /dev/null+++ b/api/tests/unit_tests/services/test_inner_mail_service.py@@ -0,0 +1,14 @@+from unittest.mock import MagicMock++from services.entities.mail_entities import InnerMailMessage+from services.inner_mail_service import InnerMailService+++def test_inner_mail_service_delegates_to_dispatcher() -> None:+ dispatch = MagicMock()+ service = InnerMailService(dispatch=dispatch)+ message = InnerMailMessage(recipients=("[email protected]",), subject="Subject", body="Body")++ service.send(message)++ dispatch.assert_called_once_with(message)diff --git a/api/tests/unit_tests/services/test_system_feature_service_app_dsl_version.py b/api/tests/unit_tests/services/test_system_feature_service_app_dsl_version.pynew file mode 100644index 00000000000..0fca8efa601--- /dev/null+++ b/api/tests/unit_tests/services/test_system_feature_service_app_dsl_version.py@@ -0,0 +1,9 @@+"""Tests for the public SystemFeatureService app DSL contract."""++from services.system_feature_service import SystemFeatureService+++def test_get_system_features_excludes_app_dsl_version() -> None:+ result = SystemFeatureService.get_public_system_features().model_dump()++ assert "app_dsl_version" not in resultdiff --git a/api/tests/unit_tests/services/test_system_feature_service_change_email.py b/api/tests/unit_tests/services/test_system_feature_service_change_email.pynew file mode 100644index 00000000000..d4cc1666c47--- /dev/null+++ b/api/tests/unit_tests/services/test_system_feature_service_change_email.py@@ -0,0 +1,37 @@+from collections.abc import Callable++import pytest++from enums import DeploymentEdition+from services.system_feature_service import SystemFeatureService++[email protected]("enabled", [False, True])+def test_get_system_features_reads_enable_change_email(+ config_overrides: Callable[..., None],+ enabled: bool,+) -> None:+ config_overrides(ENABLE_CHANGE_EMAIL=enabled)++ result = SystemFeatureService.get_public_system_features()++ assert result.enable_change_email is enabled+++ ("deployment_edition", "configured", "expected"),+ [+ (DeploymentEdition.COMMUNITY, False, False),+ (DeploymentEdition.COMMUNITY, True, True),+ (DeploymentEdition.ENTERPRISE, True, False),+ ],+)+def test_change_email_policy(+ config_overrides: Callable[..., None],+ deployment_edition: DeploymentEdition,+ configured: bool,+ expected: bool,+) -> None:+ config_overrides(DEPLOYMENT_EDITION=deployment_edition, ENABLE_CHANGE_EMAIL=configured)++ assert SystemFeatureService.is_change_email_enabled() is expecteddiff --git a/api/tests/unit_tests/services/test_feature_service_deployment_edition.py b/api/tests/unit_tests/services/test_system_feature_service_deployment_edition.pysimilarity index 81%rename from api/tests/unit_tests/services/test_feature_service_deployment_edition.pyrename to api/tests/unit_tests/services/test_system_feature_service_deployment_edition.pyindex b31e398add4..ddf4ff03538 100644--- a/api/tests/unit_tests/services/test_feature_service_deployment_edition.py+++ b/api/tests/unit_tests/services/test_system_feature_service_deployment_edition.py@@ -1,3 +1,5 @@+"""Tests for SystemFeatureService deployment-edition behavior."""+from collections.abc import Callablefrom unittest.mock import MagicMock@@ -6,7 +8,7 @@ from pydantic import ValidationErrorfrom enums import DeploymentEditionfrom services.entities.feature_entities import SystemFeatureModel-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServicedef test_system_feature_model_requires_deployment_edition() -> None:@@ -30,16 +32,16 @@ def test_get_system_features_uses_configured_deployment_edition(fulfill_from_enterprise = MagicMock()config_overrides(DEPLOYMENT_EDITION=edition)monkeypatch.setattr(- "services.feature_service.FeatureService._fulfill_params_from_enterprise",+ "services.system_feature_service.SystemFeatureService._fulfill_params_from_enterprise",fulfill_from_enterprise,)- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()assert result.deployment_edition is editionassert result.model_dump(mode="json")["deployment_edition"] == edition.valuewebapp_auth_enabled = edition is DeploymentEdition.ENTERPRISE- assert FeatureService.is_webapp_auth_enabled() is webapp_auth_enabled+ assert SystemFeatureService.is_webapp_auth_enabled() is webapp_auth_enabledassert result.webapp_auth.enabled is webapp_auth_enabledif edition is DeploymentEdition.ENTERPRISE:fulfill_from_enterprise.assert_called_once_with(result)@@ -64,4 +66,4 @@ def test_trial_app_policy_is_cloud_only() -> None:config_overrides(DEPLOYMENT_EDITION=edition, ENABLE_TRIAL_APP=feature_enabled)- assert FeatureService.is_trial_app_enabled() is expected+ assert SystemFeatureService.is_trial_app_enabled() is expecteddiff --git a/api/tests/unit_tests/services/test_feature_service_enable_app_deploy.py b/api/tests/unit_tests/services/test_system_feature_service_enable_app_deploy.pysimilarity index 78%rename from api/tests/unit_tests/services/test_feature_service_enable_app_deploy.pyrename to api/tests/unit_tests/services/test_system_feature_service_enable_app_deploy.pyindex c9aa82a443f..0741f6a6f32 100644--- a/api/tests/unit_tests/services/test_feature_service_enable_app_deploy.py+++ b/api/tests/unit_tests/services/test_system_feature_service_enable_app_deploy.py@@ -1,9 +1,11 @@+"""Tests for the SystemFeatureService app-deployment policy."""+import pytestfrom enums import DeploymentEdition-from services import feature_service as feature_service_module+from services import system_feature_service as feature_service_modulefrom services.entities.feature_entities import SystemFeatureModel-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureService@pytest.mark.parametrize(@@ -21,10 +23,10 @@ from services.feature_service import FeatureService)def test_fulfill_params_from_enterprise_enable_app_deploy(monkeypatch: pytest.MonkeyPatch,- enterprise_info: dict,+ enterprise_info: dict[str, object],initial: bool,expected: bool,-):+) -> None:monkeypatch.setattr(feature_service_module.EnterpriseService,"get_info",@@ -34,6 +36,6 @@ def test_fulfill_params_from_enterprise_enable_app_deploy(features = SystemFeatureModel(deployment_edition=DeploymentEdition.COMMUNITY)features.enable_app_deploy = initial- FeatureService._fulfill_params_from_enterprise(features)+ SystemFeatureService._fulfill_params_from_enterprise(features)assert features.enable_app_deploy is expecteddiff --git a/api/tests/unit_tests/services/test_feature_service_explore_banner.py b/api/tests/unit_tests/services/test_system_feature_service_explore_banner.pysimilarity index 67%rename from api/tests/unit_tests/services/test_feature_service_explore_banner.pyrename to api/tests/unit_tests/services/test_system_feature_service_explore_banner.pyindex ade37592777..7b6fb8ba2c1 100644--- a/api/tests/unit_tests/services/test_feature_service_explore_banner.py+++ b/api/tests/unit_tests/services/test_system_feature_service_explore_banner.py@@ -1,9 +1,11 @@+"""Tests for the SystemFeatureService explore-banner policy."""+from collections.abc import Callableimport pytestfrom enums import DeploymentEdition-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureService@pytest.mark.parametrize(@@ -23,9 +25,9 @@ def test_get_system_features_enables_explore_banner_only_for_cloud(expected: bool,) -> None:config_overrides(DEPLOYMENT_EDITION=edition, ENABLE_EXPLORE_BANNER=configured)- monkeypatch.setattr(FeatureService, "_fulfill_params_from_enterprise", lambda *_: None)+ monkeypatch.setattr(SystemFeatureService, "_fulfill_params_from_enterprise", lambda *_: None)- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()- assert FeatureService.is_explore_banner_enabled() is expected+ assert SystemFeatureService.is_explore_banner_enabled() is expectedassert result.enable_explore_banner is expecteddiff --git a/api/tests/unit_tests/services/test_system_feature_service_internal_policies.py b/api/tests/unit_tests/services/test_system_feature_service_internal_policies.pynew file mode 100644index 00000000000..4b0eebe7f0c--- /dev/null+++ b/api/tests/unit_tests/services/test_system_feature_service_internal_policies.py@@ -0,0 +1,128 @@+from collections.abc import Callable++import pytest++from enums import DeploymentEdition+from services.entities.feature_entities import LicenseStatus+from services.system_feature_service import SystemFeatureService+++def test_workspace_creation_uses_environment_policy(+ monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY, ALLOW_CREATE_WORKSPACE=True)+ monkeypatch.setattr(+ "services.system_feature_service.EnterpriseService.get_info",+ lambda: (_ for _ in ()).throw(AssertionError("enterprise API should not be called")),+ )++ assert SystemFeatureService.is_workspace_creation_allowed() is True+++def test_workspace_creation_uses_enterprise_policy(+ monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)+ monkeypatch.setattr(+ "services.system_feature_service.EnterpriseService.get_info",+ lambda: {"IsAllowCreateWorkspace": False},+ )++ assert SystemFeatureService.is_workspace_creation_allowed() is False+++def test_workspace_creation_keeps_environment_policy_when_enterprise_value_is_missing(+ monkeypatch: pytest.MonkeyPatch,+ config_overrides: Callable[..., None],+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE, ALLOW_CREATE_WORKSPACE=True)+ monkeypatch.setattr("services.system_feature_service.EnterpriseService.get_info", lambda: {})++ assert SystemFeatureService.is_workspace_creation_allowed() is True+++def test_plugin_manager_is_enabled_only_for_enterprise(config_overrides: Callable[..., None]) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)+ assert SystemFeatureService.is_plugin_manager_enabled() is True++ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)+ assert SystemFeatureService.is_plugin_manager_enabled() is False+++def test_webapp_auth_enabled_does_not_query_enterprise_info(+ monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)+ monkeypatch.setattr(+ "services.system_feature_service.EnterpriseService.get_info",+ lambda: (_ for _ in ()).throw(AssertionError("enterprise info should not be queried")),+ )++ assert SystemFeatureService.is_webapp_auth_enabled() is True+++def test_registration_policy_uses_enterprise_override(+ monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE, ALLOW_REGISTER=True)+ monkeypatch.setattr(+ "services.system_feature_service.EnterpriseService.get_info",+ lambda: {"IsAllowRegister": False},+ )++ assert SystemFeatureService.is_registration_allowed() is False+++def test_password_login_policy_uses_enterprise_override(+ monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE, ENABLE_EMAIL_PASSWORD_LOGIN=True)+ monkeypatch.setattr(+ "services.system_feature_service.EnterpriseService.get_info",+ lambda: {"EnableEmailPasswordLogin": False},+ )++ assert SystemFeatureService.is_email_password_login_enabled() is False+++def test_branding_reads_enterprise_configuration(+ monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)+ monkeypatch.setattr(+ "services.system_feature_service.EnterpriseService.get_info",+ lambda: {+ "Branding": {+ "applicationTitle": "Enterprise Dify",+ "loginPageLogo": "login-logo",+ "workspaceLogo": "workspace-logo",+ "favicon": "favicon",+ }+ },+ )++ branding = SystemFeatureService.get_branding()++ assert branding.enabled is True+ assert branding.application_title == "Enterprise Dify"+ assert branding.login_page_logo == "login-logo"+ assert branding.workspace_logo == "workspace-logo"+ assert branding.favicon == "favicon"+++def test_license_status_ignores_unrelated_malformed_quota_fields(+ monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]+) -> None:+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)+ monkeypatch.setattr(+ "services.system_feature_service.EnterpriseService.get_info",+ lambda: {+ "License": {+ "status": "active",+ "workspaces": {"enabled": True, "limit": 3, "used": {"unexpected": "shape"}},+ "licensedSeats": "unexpected-shape",+ }+ },+ )++ assert SystemFeatureService.get_license_status() == LicenseStatus.ACTIVEdiff --git a/api/tests/unit_tests/services/test_feature_service_knowledge_fs.py b/api/tests/unit_tests/services/test_system_feature_service_knowledge_fs.pysimilarity index 75%rename from api/tests/unit_tests/services/test_feature_service_knowledge_fs.pyrename to api/tests/unit_tests/services/test_system_feature_service_knowledge_fs.pyindex ecb053df260..f13813e22fb 100644--- a/api/tests/unit_tests/services/test_feature_service_knowledge_fs.py+++ b/api/tests/unit_tests/services/test_system_feature_service_knowledge_fs.py@@ -1,10 +1,12 @@+"""Tests for the SystemFeatureService knowledge-filesystem policy."""+from collections.abc import Callableimport pytestfrom enums import DeploymentEditionfrom services.entities.feature_entities import SystemFeatureModel-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServicedef test_system_feature_model_disables_knowledge_fs_by_default() -> None:@@ -18,6 +20,6 @@ def test_get_system_features_reads_knowledge_fs_flag() -> None:config_overrides(KNOWLEDGE_FS_ENABLED=enabled)- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()assert result.knowledge_fs_enabled is enableddiff --git a/api/tests/unit_tests/services/test_feature_service_learn_app.py b/api/tests/unit_tests/services/test_system_feature_service_learn_app.pysimilarity index 69%rename from api/tests/unit_tests/services/test_feature_service_learn_app.pyrename to api/tests/unit_tests/services/test_system_feature_service_learn_app.pyindex ed58e27086d..95e53bb51aa 100644--- a/api/tests/unit_tests/services/test_feature_service_learn_app.py+++ b/api/tests/unit_tests/services/test_system_feature_service_learn_app.py@@ -1,13 +1,15 @@+"""Tests for SystemFeatureService learn-app and tour policies."""+from collections.abc import Callableimport pytestfrom enums import DeploymentEditionfrom services.entities.feature_entities import SystemFeatureModel-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureService-def test_system_feature_model_defaults_enable_learn_app():+def test_system_feature_model_defaults_enable_learn_app() -> None:system_features = SystemFeatureModel(deployment_edition=DeploymentEdition.COMMUNITY)assert system_features.enable_learn_app is True@@ -15,10 +17,10 @@ def test_system_feature_model_defaults_enable_learn_app():@pytest.mark.parametrize("enabled", [True, False])-def test_get_system_features_reads_enable_learn_app(config_overrides: Callable[..., None], enabled: bool):+def test_get_system_features_reads_enable_learn_app(config_overrides: Callable[..., None], enabled: bool) -> None:config_overrides(ENABLE_LEARN_APP=enabled)- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()assert result.enable_learn_app is enabled@@ -29,6 +31,6 @@ def test_get_system_features_reads_enable_step_by_step_tour() -> None:config_overrides(ENABLE_STEP_BY_STEP_TOUR=enabled)- result = FeatureService.get_system_features()+ result = SystemFeatureService.get_public_system_features()assert result.enable_step_by_step_tour is enableddiff --git a/api/tests/unit_tests/services/test_feature_service_license_expiry_notice.py b/api/tests/unit_tests/services/test_system_feature_service_license_expiry_notice.pysimilarity index 85%rename from api/tests/unit_tests/services/test_feature_service_license_expiry_notice.pyrename to api/tests/unit_tests/services/test_system_feature_service_license_expiry_notice.pyindex dac43f83706..0ca89ae1933 100644--- a/api/tests/unit_tests/services/test_feature_service_license_expiry_notice.py+++ b/api/tests/unit_tests/services/test_system_feature_service_license_expiry_notice.py@@ -1,11 +1,13 @@+"""Tests for the SystemFeatureService license-expiry policy."""+from collections.abc import Callableimport pytestfrom enums import DeploymentEdition-from services import feature_service as feature_service_module+from services import system_feature_service as feature_service_modulefrom services.entities.feature_entities import LicenseModel, LicenseStatus-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureService_ENTERPRISE_INFO = {"License": {"status": LicenseStatus.EXPIRING, "expiredAt": "2026-12-31"}}@@ -25,7 +27,7 @@ def test_get_license_non_enterprise_ignores_expiry_notice_config(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY,)- result = FeatureService.get_license()+ result = SystemFeatureService.get_license()assert result.license_expiry_notice_enabled is False@@ -45,7 +47,7 @@ def test_get_license_enterprise_reads_license_expiry_notice_enabled(staticmethod(lambda: _ENTERPRISE_INFO),)- result = FeatureService.get_license()+ result = SystemFeatureService.get_license()assert result.status == LicenseStatus.EXPIRINGassert result.expired_at == "2026-12-31"diff --git a/api/tests/unit_tests/services/test_feature_service_licensed_seats.py b/api/tests/unit_tests/services/test_system_feature_service_licensed_seats.pysimilarity index 70%rename from api/tests/unit_tests/services/test_feature_service_licensed_seats.pyrename to api/tests/unit_tests/services/test_system_feature_service_licensed_seats.pyindex 9df759a8f6a..a3f07e2e2ef 100644--- a/api/tests/unit_tests/services/test_feature_service_licensed_seats.py+++ b/api/tests/unit_tests/services/test_system_feature_service_licensed_seats.py@@ -1,16 +1,20 @@+"""Tests for SystemFeatureService licensed-seat parsing."""+from collections.abc import Callableimport pytestfrom enums import DeploymentEdition-from services import feature_service as feature_service_module+from services import system_feature_service as feature_service_modulefrom services.entities.feature_entities import LicenseModel, LicenseStatus-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureService_ENTERPRISE_INFO = {"License": {"licensedSeats": {"enabled": True, "limit": 3, "used": 1}}}-def test_get_license_parses_licensed_seats(monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]):+def test_get_license_parses_licensed_seats(+ monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]+) -> None:"""The authenticated license accessor copies the licensed-seat quota out of the enterprise payload."""config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)monkeypatch.setattr(@@ -19,7 +23,7 @@ def test_get_license_parses_licensed_seats(monkeypatch: pytest.MonkeyPatch, confstaticmethod(lambda: _ENTERPRISE_INFO),)- license_model = FeatureService.get_license()+ license_model = SystemFeatureService.get_license()assert isinstance(license_model, LicenseModel)assert license_model.seats.enabled is True@@ -27,11 +31,11 @@ def test_get_license_parses_licensed_seats(monkeypatch: pytest.MonkeyPatch, confassert license_model.seats.size == 1-def test_get_license_non_enterprise_is_unconstrained(config_overrides: Callable[..., None]):+def test_get_license_non_enterprise_is_unconstrained(config_overrides: Callable[..., None]) -> None:"""Non-enterprise deployments have no license; seat allocation is unconstrained."""config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)- license_model = FeatureService.get_license()+ license_model = SystemFeatureService.get_license()assert license_model.status == LicenseStatus.NONEassert license_model.seats.enabled is Falsediff --git a/api/tests/unit_tests/services/test_feature_service_plugin_installation_permission.py b/api/tests/unit_tests/services/test_system_feature_service_plugin_installation_permission.pysimilarity index 83%rename from api/tests/unit_tests/services/test_feature_service_plugin_installation_permission.pyrename to api/tests/unit_tests/services/test_system_feature_service_plugin_installation_permission.pyindex 4ec58c793ee..cc2490b6983 100644--- a/api/tests/unit_tests/services/test_feature_service_plugin_installation_permission.py+++ b/api/tests/unit_tests/services/test_system_feature_service_plugin_installation_permission.py@@ -1,12 +1,14 @@+"""Tests for SystemFeatureService plugin-installation policy."""+import loggingfrom collections.abc import Callableimport pytestfrom enums import DeploymentEdition-from services import feature_service as feature_service_module+from services import system_feature_service as feature_service_modulefrom services.entities.feature_entities import PluginInstallationScope, SystemFeatureModel-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServicedef test_get_plugin_installation_permission_defaults_to_all_for_non_enterprise(@@ -14,7 +16,7 @@ def test_get_plugin_installation_permission_defaults_to_all_for_non_enterprise() -> None:config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)- permission = FeatureService.get_plugin_installation_permission()+ permission = SystemFeatureService.get_plugin_installation_permission()assert permission.plugin_installation_scope is PluginInstallationScope.ALLassert permission.restrict_to_marketplace_only is False@@ -38,7 +40,7 @@ def test_get_plugin_installation_permission_parses_enterprise_policy(),)- permission = FeatureService.get_plugin_installation_permission()+ permission = SystemFeatureService.get_plugin_installation_permission()assert permission.plugin_installation_scope is PluginInstallationScope.OFFICIAL_ONLYassert permission.restrict_to_marketplace_only is True@@ -62,8 +64,8 @@ def test_invalid_enterprise_policy_denies_all_plugin_installations(caplog: pytest.LogCaptureFixture,invalid_permission: dict[str, object],) -> None:- with caplog.at_level(logging.ERROR, logger="services.feature_service"):- permission = FeatureService._resolve_plugin_installation_permission(+ with caplog.at_level(logging.ERROR, logger="services.system_feature_service"):+ permission = SystemFeatureService._resolve_plugin_installation_permission({"PluginInstallationPermission": invalid_permission})@@ -89,7 +91,7 @@ def test_system_features_exposes_only_validated_plugin_installation_policy()features = SystemFeatureModel(deployment_edition=DeploymentEdition.ENTERPRISE)- FeatureService._fulfill_params_from_enterprise(features)+ SystemFeatureService._fulfill_params_from_enterprise(features)assert features.plugin_installation_permission.plugin_installation_scope is PluginInstallationScope.NONEassert features.plugin_installation_permission.restrict_to_marketplace_only is Truediff --git a/api/tests/unit_tests/services/test_feature_service_sso_protocol.py b/api/tests/unit_tests/services/test_system_feature_service_sso_protocol.pysimilarity index 84%rename from api/tests/unit_tests/services/test_feature_service_sso_protocol.pyrename to api/tests/unit_tests/services/test_system_feature_service_sso_protocol.pyindex 0177239077c..b889282e24b 100644--- a/api/tests/unit_tests/services/test_feature_service_sso_protocol.py+++ b/api/tests/unit_tests/services/test_system_feature_service_sso_protocol.py@@ -1,11 +1,13 @@+"""Tests for SystemFeatureService SSO protocol parsing."""+import loggingimport pytestfrom enums import DeploymentEdition-from services import feature_service as feature_service_module+from services import system_feature_service as feature_service_modulefrom services.entities.feature_entities import SSOProtocol, SystemFeatureModel-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureServicedef test_system_features_exposes_valid_enterprise_sso_protocols(@@ -24,7 +26,7 @@ def test_system_features_exposes_valid_enterprise_sso_protocols()features = SystemFeatureModel(deployment_edition=DeploymentEdition.ENTERPRISE)- FeatureService._fulfill_params_from_enterprise(features)+ SystemFeatureService._fulfill_params_from_enterprise(features)assert features.sso_enforced_for_signin_protocol is SSOProtocol.SAMLassert features.webapp_auth.sso_config.protocol is SSOProtocol.OIDC@@ -48,7 +50,7 @@ def test_system_features_normalizes_empty_enterprise_sso_protocols_to_none()features = SystemFeatureModel(deployment_edition=DeploymentEdition.ENTERPRISE)- FeatureService._fulfill_params_from_enterprise(features)+ SystemFeatureService._fulfill_params_from_enterprise(features)assert features.sso_enforced_for_signin_protocol is Noneassert features.webapp_auth.sso_config.protocol is None@@ -73,8 +75,8 @@ def test_system_features_rejects_invalid_enterprise_sso_protocols()features = SystemFeatureModel(deployment_edition=DeploymentEdition.ENTERPRISE)- with caplog.at_level(logging.ERROR, logger="services.feature_service"):- FeatureService._fulfill_params_from_enterprise(features)+ with caplog.at_level(logging.ERROR, logger="services.system_feature_service"):+ SystemFeatureService._fulfill_params_from_enterprise(features)assert features.sso_enforced_for_signin_protocol is Noneassert features.webapp_auth.sso_config.protocol is Nonediff --git a/api/tests/unit_tests/services/test_system_feature_service_trial_models.py b/api/tests/unit_tests/services/test_system_feature_service_trial_models.pynew file mode 100644index 00000000000..8760f79da7b--- /dev/null+++ b/api/tests/unit_tests/services/test_system_feature_service_trial_models.py@@ -0,0 +1,9 @@+"""Tests for the public SystemFeatureService hosted-model contract."""++from services.system_feature_service import SystemFeatureService+++def test_get_system_features_excludes_trial_models() -> None:+ result = SystemFeatureService.get_public_system_features().model_dump()++ assert "trial_models" not in resultdiff --git a/api/tests/unit_tests/services/test_feature_service_webapp_public_access.py b/api/tests/unit_tests/services/test_system_feature_service_webapp_public_access.pysimilarity index 73%rename from api/tests/unit_tests/services/test_feature_service_webapp_public_access.pyrename to api/tests/unit_tests/services/test_system_feature_service_webapp_public_access.pyindex ba6bc45c357..69757ebd7cd 100644--- a/api/tests/unit_tests/services/test_feature_service_webapp_public_access.py+++ b/api/tests/unit_tests/services/test_system_feature_service_webapp_public_access.py@@ -1,10 +1,12 @@+"""Tests for the SystemFeatureService WebApp public-access policy."""+from collections.abc import Callableimport pytestfrom enums import DeploymentEditionfrom services.entities.feature_entities import SystemFeatureModel-from services.feature_service import FeatureService+from services.system_feature_service import SystemFeatureService@pytest.mark.parametrize(@@ -19,16 +21,16 @@ def test_fulfill_system_params_from_env_sets_allow_public_access(config_overrides: Callable[..., None],env_value: bool,expected: bool,-):+) -> None:config_overrides(WEBAPP_PUBLIC_ACCESS_ENABLED=env_value)system_features = SystemFeatureModel(deployment_edition=DeploymentEdition.COMMUNITY)- FeatureService._fulfill_system_params_from_env(system_features)+ SystemFeatureService._fulfill_system_params_from_env(system_features)assert system_features.webapp_auth.allow_public_access is expected-def test_get_system_features_defaults_allow_public_access_to_true():- system_features = FeatureService.get_system_features()+def test_get_system_features_defaults_allow_public_access_to_true() -> None:+ system_features = SystemFeatureService.get_public_system_features()assert system_features.webapp_auth.allow_public_access is Truediff --git a/api/tests/unit_tests/services/test_web_passport_gateways.py b/api/tests/unit_tests/services/test_web_passport_gateways.pynew file mode 100644index 00000000000..48806681a18--- /dev/null+++ b/api/tests/unit_tests/services/test_web_passport_gateways.py@@ -0,0 +1,72 @@+"""Unit tests for the outer gateways used by web passport issuance."""++from unittest.mock import MagicMock++import pytest+from werkzeug.exceptions import Unauthorized++from services.enterprise.enterprise_service import WebAppAccessMode, WebAppSettings+from services.web_passport_gateways import DeploymentWebPassportAuthGateway, PassportTokenGateway+from services.web_passport_service import WebAppAuthType, WebPassportUnauthorizedError+++def test_deployment_auth_gateway_reads_deployment_setting() -> None:+ gateway = DeploymentWebPassportAuthGateway(+ webapp_auth_enabled=True,+ get_app_access_mode=MagicMock(),+ )++ assert gateway.is_webapp_auth_enabled() is True+++ ("access_mode", "expected"),+ [+ (WebAppAccessMode.PUBLIC, WebAppAuthType.PUBLIC),+ (WebAppAccessMode.PRIVATE, WebAppAuthType.INTERNAL),+ (WebAppAccessMode.PRIVATE_ALL, WebAppAuthType.INTERNAL),+ (WebAppAccessMode.SSO_VERIFIED, WebAppAuthType.EXTERNAL),+ ],+)+def test_deployment_auth_gateway_delegates_access_mode_mapping(+ access_mode: WebAppAccessMode,+ expected: WebAppAuthType,+) -> None:+ get_access_mode = MagicMock(return_value=WebAppSettings(accessMode=access_mode))+ gateway = DeploymentWebPassportAuthGateway(+ webapp_auth_enabled=True,+ get_app_access_mode=get_access_mode,+ )++ assert gateway.get_app_auth_type("app-1") == expected+ get_access_mode.assert_called_once_with("app-1")+++def test_passport_token_gateway_delegates_issue_and_verify() -> None:+ passport = MagicMock()+ passport.verify.return_value = {"sub": "account-1"}+ passport.issue.return_value = "issued-token"+ gateway = PassportTokenGateway(passport=passport)++ assert gateway.verify("input-token") == {"sub": "account-1"}+ assert gateway.issue({"sub": "account-1"}) == "issued-token"+ passport.verify.assert_called_once_with("input-token")+ passport.issue.assert_called_once_with({"sub": "account-1"})+++def test_passport_token_gateway_translates_unauthorized() -> None:+ passport = MagicMock()+ passport.verify.side_effect = Unauthorized("Token has expired.")+ gateway = PassportTokenGateway(passport=passport)++ with pytest.raises(WebPassportUnauthorizedError, match="Token has expired"):+ gateway.verify("expired-token")+++def test_passport_token_gateway_defaults_empty_unauthorized_description() -> None:+ passport = MagicMock()+ passport.verify.side_effect = Unauthorized("")+ gateway = PassportTokenGateway(passport=passport)++ with pytest.raises(WebPassportUnauthorizedError, match="Invalid token"):+ gateway.verify("invalid-token")diff --git a/api/tests/unit_tests/services/test_web_passport_service.py b/api/tests/unit_tests/services/test_web_passport_service.pynew file mode 100644index 00000000000..446d4ead07d--- /dev/null+++ b/api/tests/unit_tests/services/test_web_passport_service.py@@ -0,0 +1,243 @@+from datetime import UTC, datetime+from unittest.mock import MagicMock++import pytest++from services.entities.passport_entities import (+ EndUserRecord,+ WebAppRecord,+ WebPassportEndUserResolution,+ WebPassportRequest,+)+from services.web_passport_service import (+ WebAppAuthType,+ WebPassportAuthenticationRequiredError,+ WebPassportNotFoundError,+ WebPassportService,+ WebPassportUnauthorizedError,+)++APP = WebAppRecord(site_id="site-1", app_id="app-1", tenant_id="tenant-1", app_code="app-code")+NOW = datetime(2026, 8, 13, 12, 0, tzinfo=UTC)+++def _service(+ *,+ repository: MagicMock | None = None,+ auth: MagicMock | None = None,+ tokens: MagicMock | None = None,+) -> tuple[WebPassportService, MagicMock, MagicMock, MagicMock]:+ if repository is None:+ repository = MagicMock()+ repository.get_active_web_app.return_value = APP+ repository.is_web_app_active.return_value = True+ resolution = WebPassportEndUserResolution(app_active=True, end_user=EndUserRecord(id="end-user-1"))+ repository.resolve_standard_end_user.return_value = resolution+ repository.resolve_authenticated_end_user.return_value = resolution+ if auth is None:+ auth = MagicMock()+ auth.is_webapp_auth_enabled.return_value = False+ if tokens is None:+ tokens = MagicMock()+ tokens.issue.return_value = "issued-token"+ now = MagicMock(return_value=NOW)+ service = WebPassportService(+ passports=repository,+ auth=auth,+ tokens=tokens,+ now=now,+ access_token_expire_minutes=60,+ )+ return service, repository, auth, tokens+++def _request(*, user_session_id: str | None = None, access_token: str | None = None) -> WebPassportRequest:+ return WebPassportRequest(app_code="app-code", user_session_id=user_session_id, access_token=access_token)+++def test_issue_creates_anonymous_user_and_standard_passport() -> None:+ service, repository, _auth, tokens = _service()++ result = service.issue(_request())++ assert result.access_token == "issued-token"+ repository.resolve_standard_end_user.assert_called_once_with(APP, None)+ tokens.issue.assert_called_once_with(+ {+ "iss": "app-1",+ "sub": "Web API Passport",+ "app_id": "app-1",+ "app_code": "app-code",+ "end_user_id": "end-user-1",+ }+ )+++def test_issue_reuses_requested_session_user() -> None:+ service, repository, _auth, _tokens = _service()++ service.issue(_request(user_session_id="existing-session"))++ repository.resolve_standard_end_user.assert_called_once_with(APP, "existing-session")+++def test_issue_returns_not_found_for_inactive_app() -> None:+ repository = MagicMock()+ repository.get_active_web_app.return_value = None+ service, _repository, auth, _tokens = _service(repository=repository)++ with pytest.raises(WebPassportNotFoundError):+ service.issue(_request())++ auth.is_webapp_auth_enabled.assert_not_called()+++def test_issue_revalidates_app_after_enterprise_io() -> None:+ auth = MagicMock()+ auth.is_webapp_auth_enabled.return_value = True+ auth.get_app_auth_type.return_value = WebAppAuthType.INTERNAL+ tokens = MagicMock()+ tokens.verify.return_value = {+ "token_source": "webapp_login_token",+ "auth_type": "internal",+ "session_id": "session-1",+ }+ service, repository, _auth, _tokens = _service(auth=auth, tokens=tokens)++ def app_is_active(_app: WebAppRecord) -> bool:+ auth.get_app_auth_type.assert_called_once_with(APP.app_id)+ return False++ repository.is_web_app_active.side_effect = app_is_active++ with pytest.raises(WebPassportNotFoundError):+ service.issue(_request(access_token="login-token"))++ repository.resolve_authenticated_end_user.assert_not_called()+ tokens.issue.assert_not_called()+++def test_issue_returns_not_found_when_app_becomes_inactive_before_user_creation() -> None:+ service, repository, _auth, tokens = _service()+ repository.resolve_standard_end_user.return_value = WebPassportEndUserResolution(+ app_active=False,+ end_user=None,+ )++ with pytest.raises(WebPassportNotFoundError):+ service.issue(_request())++ tokens.issue.assert_not_called()+++def test_issue_requires_login_for_private_webapp() -> None:+ auth = MagicMock()+ auth.is_webapp_auth_enabled.return_value = True+ auth.get_app_auth_type.return_value = WebAppAuthType.INTERNAL+ service, _repository, _auth, _tokens = _service(auth=auth)++ with pytest.raises(WebPassportAuthenticationRequiredError):+ service.issue(_request())+++def test_issue_rejects_wrong_login_token_source() -> None:+ auth = MagicMock()+ auth.is_webapp_auth_enabled.return_value = True+ auth.get_app_auth_type.return_value = WebAppAuthType.INTERNAL+ tokens = MagicMock()+ tokens.verify.return_value = {"token_source": "other"}+ service, _repository, _auth, _tokens = _service(auth=auth, tokens=tokens)++ with pytest.raises(WebPassportUnauthorizedError, match="token source"):+ service.issue(_request(access_token="login-token"))+++def test_issue_rejects_auth_type_mismatch() -> None:+ auth = MagicMock()+ auth.is_webapp_auth_enabled.return_value = True+ auth.get_app_auth_type.return_value = WebAppAuthType.EXTERNAL+ tokens = MagicMock()+ tokens.verify.return_value = {+ "token_source": "webapp_login_token",+ "auth_type": "internal",+ "session_id": "session-1",+ }+ service, _repository, _auth, _tokens = _service(auth=auth, tokens=tokens)++ with pytest.raises(WebPassportAuthenticationRequiredError, match="external"):+ service.issue(_request(access_token="login-token"))+++def test_issue_exchanges_enterprise_token_after_user_resolution() -> None:+ auth = MagicMock()+ auth.is_webapp_auth_enabled.return_value = True+ auth.get_app_auth_type.return_value = WebAppAuthType.INTERNAL+ tokens = MagicMock()+ tokens.verify.return_value = {+ "token_source": "webapp_login_token",+ "user_id": "account-1",+ "end_user_id": "stale-end-user",+ "session_id": "session-1",+ "auth_type": "internal",+ "exp": 2_000_000_000,+ }+ tokens.issue.return_value = "enterprise-token"+ service, repository, _auth, _tokens = _service(auth=auth, tokens=tokens)+ repository.resolve_authenticated_end_user.return_value = WebPassportEndUserResolution(+ app_active=True,+ end_user=EndUserRecord(id="end-user-by-session"),+ )++ result = service.issue(_request(access_token="login-token"))++ assert result.access_token == "enterprise-token"+ repository.resolve_authenticated_end_user.assert_called_once_with(+ APP,+ end_user_id="stale-end-user",+ session_id="session-1",+ )+ tokens.issue.assert_called_once_with(+ {+ "iss": "site-1",+ "sub": "Web API Passport",+ "app_id": "app-1",+ "app_code": "app-code",+ "user_id": "account-1",+ "end_user_id": "end-user-by-session",+ "auth_type": "internal",+ "granted_at": int(NOW.timestamp()),+ "token_source": "webapp",+ "exp": 2_000_000_000,+ }+ )+++def test_issue_requires_session_id_when_enterprise_user_is_missing() -> None:+ auth = MagicMock()+ auth.is_webapp_auth_enabled.return_value = True+ auth.get_app_auth_type.return_value = WebAppAuthType.INTERNAL+ tokens = MagicMock()+ tokens.verify.return_value = {"token_source": "webapp_login_token", "auth_type": "internal"}+ service, repository, _auth, _tokens = _service(auth=auth, tokens=tokens)+ repository.resolve_authenticated_end_user.return_value = WebPassportEndUserResolution(+ app_active=True,+ end_user=None,+ )++ with pytest.raises(WebPassportNotFoundError, match="Missing session_id"):+ service.issue(_request(access_token="login-token"))+++def test_public_webapp_verifies_optional_login_token_then_uses_standard_flow() -> None:+ auth = MagicMock()+ auth.is_webapp_auth_enabled.return_value = True+ auth.get_app_auth_type.return_value = WebAppAuthType.PUBLIC+ tokens = MagicMock()+ tokens.verify.return_value = {"token_source": "webapp_login_token"}+ tokens.issue.return_value = "public-token"+ service, _repository, _auth, _tokens = _service(auth=auth, tokens=tokens)++ service.issue(_request(access_token="login-token"))++ tokens.verify.assert_called_once_with("login-token")+ assert tokens.issue.call_args.args[0]["iss"] == "app-1"diff --git a/api/tests/unit_tests/services/test_workflow_service.py b/api/tests/unit_tests/services/test_workflow_service.pyindex 5d4e3d92ced..da1ea117964 100644--- a/api/tests/unit_tests/services/test_workflow_service.py+++ b/api/tests/unit_tests/services/test_workflow_service.py@@ -1469,8 +1469,8 @@ class TestWorkflowService:with (patch(- "services.feature_service.FeatureService.get_system_features",- return_value=SimpleNamespace(plugin_manager=SimpleNamespace(enabled=False)),+ "services.system_feature_service.SystemFeatureService.is_plugin_manager_enabled",+ return_value=False,),pytest.raises(ValueError, match=error),):