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): move account access behind application services (#40437)
Byron.wang1d79b873079c
diff --git a/api/.importlinter b/api/.importlinterindex 2de7120977d..780a8e03035 100644--- a/api/.importlinter+++ b/api/.importlinter@@ -97,7 +97,10 @@ forbidden_modules =name = Account application services and contracts are framework and persistence neutraltype = forbiddensource_modules =+ services.account_avatar_serviceservices.account_errors+ services.account_integration_service+ services.account_password_serviceservices.account_portsservices.account_profile_serviceservices.entities.account_entitiesdiff --git a/api/controllers/console/workspace/account.py b/api/controllers/console/workspace/account.pyindex 5ce0494be80..40368033045 100644--- a/api/controllers/console/workspace/account.py+++ b/api/controllers/console/workspace/account.py@@ -40,13 +40,13 @@ from controllers.console.workspace.error import (AccountAlreadyInitedError,CurrentPasswordIncorrectError,InvalidAccountDeletionCodeError,+ InvalidAccountPasswordRequestError,InvalidInvitationCodeError,RepeatPasswordNotMatchError,)from controllers.console.wraps import (account_initialization_required,enable_change_email,- enterprise_license_required,model_validate,only_edition_cloud,setup_required,@@ -57,15 +57,12 @@ from extensions.ext_application_services import application_servicesfrom extensions.ext_database import dbfrom fields.base import ResponseModelfrom fields.member_fields import AccountResponse-from graphon.file import helpers as file_helpersfrom libs.datetime_utils import naive_utc_nowfrom libs.helper import EmailStr, dump_response, extract_remote_ip, timezone, to_timestampfrom libs.login import login_requiredfrom machinery.context import RequestContext-from models import Account, AccountIntegrate, InvitationCode+from models import Account, InvitationCodefrom models.account import AccountStatus, InvitationCodeStatus-from models.enums import CreatorUserRole-from models.model import UploadFilefrom services import account_errorsfrom services.account_service import AccountServicefrom services.billing_service import BillingService@@ -76,7 +73,6 @@ from services.entities.auth_entities import (ChangeEmailOldEmailToken,ChangeEmailOldEmailVerifiedToken,)-from services.errors.account import CurrentPasswordIncorrectError as ServiceCurrentPasswordIncorrectErrorclass AccountInitPayload(BaseModel):@@ -352,14 +348,14 @@ class AccountInitApi(Resource):@console_ns.route("/account/profile")class AccountProfileApi(Resource):- @setup_required- @login_required- @account_initialization_required@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[AccountResponse.__name__])- @enterprise_license_required- @with_current_user- def get(self, current_user: Account):- return dump_response(AccountResponse, current_user)+ @console_account_admission(require_valid_enterprise_license=True)+ def get(self, request_context: RequestContext):+ try:+ account = application_services().accounts.profile.get(request_context)+ except account_errors.AccountNotFoundError as error:+ raise AccountNotFound() from error+ return dump_response(AccountResponse, account)@console_ns.expect(console_ns.models[AccountProfilePatchPayload.__name__])@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[AccountResponse.__name__])@@ -391,25 +387,13 @@ class AccountAvatarApi(Resource):@console_ns.doc(description="Get account avatar url")@console_ns.doc(params=query_params_from_model(AccountAvatarQuery))@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[AvatarUrlResponse.__name__])- @setup_required- @login_required- @account_initialization_required- @with_current_user+ @console_account_admission()@model_validate(AccountAvatarQuery)- def get(self, req_data: AccountAvatarQuery, current_user: Account):- avatar = req_data.avatar-- if avatar.startswith(("http://", "https://")):- return AvatarUrlResponse(avatar_url=avatar).model_dump(mode="json")-- upload_file = db.session.scalar(select(UploadFile).where(UploadFile.id == avatar).limit(1))- if upload_file is None:- raise NotFound("Avatar file not found")-- if upload_file.created_by_role != CreatorUserRole.ACCOUNT or upload_file.created_by != current_user.id:- raise NotFound("Avatar file not found")-- avatar_url = file_helpers.get_signed_file_url(upload_file_id=upload_file.id)+ def get(self, args: AccountAvatarQuery, request_context: RequestContext):+ try:+ avatar_url = application_services().accounts.avatar.resolve(request_context, args.avatar)+ except account_errors.AvatarFileNotFoundError as error:+ raise NotFound("Avatar file not found") from errorreturn AvatarUrlResponse(avatar_url=avatar_url).model_dump(mode="json")@console_ns.expect(console_ns.models[AccountAvatarPayload.__name__])@@ -481,61 +465,46 @@ class AccountTimezoneApi(Resource):@console_ns.route("/account/password")class AccountPasswordApi(Resource):@console_ns.expect(console_ns.models[AccountPasswordPayload.__name__])- @setup_required- @login_required- @account_initialization_required@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[AccountResponse.__name__])- @with_current_user- def post(self, current_user: Account):+ @console_account_admission()+ def post(self, request_context: RequestContext):payload = console_ns.payload or {}args = AccountPasswordPayload.model_validate(payload)try:assert args.password is not None- AccountService.update_account_password(current_user, args.password, args.new_password, session=db.session())- except ServiceCurrentPasswordIncorrectError:- raise CurrentPasswordIncorrectError()+ account = application_services().accounts.password.change(+ request_context,+ current_password=args.password,+ new_password=args.new_password,+ )+ except account_errors.CurrentAccountPasswordIncorrectError as error:+ raise CurrentPasswordIncorrectError() from error+ except account_errors.InvalidAccountPasswordError as error:+ raise InvalidAccountPasswordRequestError(description=str(error)) from error+ except account_errors.AccountNotFoundError as error:+ raise AccountNotFound() from error- return dump_response(AccountResponse, current_user)+ return dump_response(AccountResponse, account)@console_ns.route("/account/integrates")class AccountIntegrateApi(Resource):- @setup_required- @login_required- @account_initialization_required@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[AccountIntegrateListResponse.__name__])- @with_current_user- def get(self, account: Account):- account_integrates = db.session.scalars(- select(AccountIntegrate).where(AccountIntegrate.account_id == account.id)- ).all()-+ @console_account_admission()+ def get(self, request_context: RequestContext):base_url = request.url_root.rstrip("/")oauth_base_path = "/console/api/oauth/login"- providers = ["github", "google"]-- integrate_data: list[AccountIntegrateResponse] = []- for provider in providers:- existing_integrate = next((ai for ai in account_integrates if ai.provider == provider), None)- if existing_integrate:- integrate_data.append(- AccountIntegrateResponse(- provider=provider,- created_at=to_timestamp(existing_integrate.created_at),- is_bound=True,- link=None,- )- )- else:- integrate_data.append(- AccountIntegrateResponse(- provider=provider,- created_at=None,- is_bound=False,- link=f"{base_url}{oauth_base_path}/{provider}",- )- )+ integrations = application_services().accounts.integrations.list(request_context)+ integrate_data = [+ AccountIntegrateResponse(+ provider=integration.provider,+ created_at=to_timestamp(integration.created_at),+ is_bound=integration.is_bound,+ link=(None if integration.is_bound else f"{base_url}{oauth_base_path}/{integration.provider}"),+ )+ for integration in integrations+ ]return AccountIntegrateListResponse(data=integrate_data).model_dump(mode="json")diff --git a/api/controllers/console/workspace/error.py b/api/controllers/console/workspace/error.pyindex a19528eb9a8..f92aeb6c5ae 100644--- a/api/controllers/console/workspace/error.py+++ b/api/controllers/console/workspace/error.py@@ -19,6 +19,12 @@ class CurrentPasswordIncorrectError(BaseHTTPException):code = 400+class InvalidAccountPasswordRequestError(BaseHTTPException):+ error_code = "invalid_account_password"+ description = "The password does not satisfy the account password policy."+ code = 400++class InvalidInvitationCodeError(BaseHTTPException):error_code = "invalid_invitation_code"description = "Invalid invitation code."diff --git a/api/extensions/ext_application_services.py b/api/extensions/ext_application_services.pyindex 37e4fcdcda9..bfb4c98fc93 100644--- a/api/extensions/ext_application_services.py+++ b/api/extensions/ext_application_services.py@@ -16,6 +16,7 @@ from core.schemas.schema_manager import SchemaManagerfrom enums import DeploymentEdition, WebAppAccessModefrom extensions.ext_redis import RedisClientWrapper, redis_clientfrom repositories.account_activation_repository import SQLAlchemyAccountActivationRepository+from repositories.account_integration_repository import SQLAlchemyAccountIntegrationRepositoryfrom repositories.account_repository import SQLAlchemyAccountRepositoryfrom repositories.app_definition_query_repository import AppDefinitionQueryRepositoryfrom repositories.data_source_api_key_auth_repository import SQLAlchemyDataSourceApiKeyAuthBindingRepository@@ -35,6 +36,11 @@ from services.account_activation_adapters import (RegisterServiceInvitationTokenStore,)from services.account_activation_service import AccountActivationService+from services.account_avatar_file_gateway import SQLAlchemyAccountAvatarFileGateway+from services.account_avatar_service import AccountAvatarService+from services.account_integration_service import AccountIntegrationService+from services.account_password_hasher import LegacyAccountPasswordHasher+from services.account_password_service import AccountPasswordServicefrom services.account_profile_service import AccountProfileServicefrom services.app_definition_query_service import AppDefinitionQueryServicefrom services.auth.data_source_api_key_auth_gateways import (@@ -94,6 +100,9 @@ def _is_user_allowed_to_access_webapp(user_id: str, app_id: str) -> bool:@dataclass(frozen=True, slots=True)class AccountServices:+ avatar: AccountAvatarService+ integrations: AccountIntegrationService+ password: AccountPasswordServiceprofile: AccountProfileService@@ -128,6 +137,8 @@ def build_application_services(data_source_api_key_auth_bindings = SQLAlchemyDataSourceApiKeyAuthBindingRepository(session_factory=database_client)app_definition_repository = AppDefinitionQueryRepository(session_factory=database_client)feature_gateway = FeatureServiceGateway()+ accounts = SQLAlchemyAccountRepository(session_factory=database_client)+ integrations = SQLAlchemyAccountIntegrationRepository(session_factory=database_client)trial_app_enabled = FeatureService.is_trial_app_enabled()database_catalog = DatabaseRecommendedAppCatalogRepository(session_factory=database_client, redis=redis)builtin_catalog = BuiltinRecommendedAppCatalogGateway()@@ -139,7 +150,15 @@ def build_application_services()return ApplicationServices(accounts=AccountServices(- profile=AccountProfileService(accounts=SQLAlchemyAccountRepository(database_client)),+ avatar=AccountAvatarService(+ files=SQLAlchemyAccountAvatarFileGateway(session_factory=database_client),+ ),+ integrations=AccountIntegrationService(integrations=integrations),+ password=AccountPasswordService(+ accounts=accounts,+ passwords=LegacyAccountPasswordHasher(),+ ),+ profile=AccountProfileService(accounts=accounts),),account_activation=AccountActivationService(tokens=RegisterServiceInvitationTokenStore(),diff --git a/api/repositories/account_integration_repository.py b/api/repositories/account_integration_repository.pynew file mode 100644index 00000000000..949d6a2e408--- /dev/null+++ b/api/repositories/account_integration_repository.py@@ -0,0 +1,25 @@+"""SQLAlchemy implementation of the account integration persistence port."""++from typing import override++from sqlalchemy import select+from sqlalchemy.orm import Session, sessionmaker++from models.account import AccountIntegrate+from services.account_ports import AccountIntegrationRepository+from services.entities.account_entities import AccountIntegrationSnapshot+++class SQLAlchemyAccountIntegrationRepository(AccountIntegrationRepository):+ def __init__(self, session_factory: sessionmaker[Session]) -> None:+ self._session_factory = session_factory++ @override+ def list_for_account(self, account_id: str) -> list[AccountIntegrationSnapshot]:+ with self._session_factory() as session:+ rows = session.execute(+ select(AccountIntegrate.provider, AccountIntegrate.created_at).where(+ AccountIntegrate.account_id == account_id+ )+ ).all()+ return [AccountIntegrationSnapshot(provider=row.provider, created_at=row.created_at) for row in rows]diff --git a/api/repositories/account_repository.py b/api/repositories/account_repository.pyindex 638f47abf44..bb1ba0efa41 100644--- a/api/repositories/account_repository.py+++ b/api/repositories/account_repository.py@@ -6,7 +6,12 @@ from sqlalchemy.orm import Session, sessionmakerfrom models.account import Accountfrom services.account_ports import AccountRepository-from services.entities.account_entities import AccountProfileChanges, AccountSnapshot+from services.entities.account_entities import (+ AccountCredentials,+ AccountPasswordDigest,+ AccountProfileChanges,+ AccountSnapshot,+)class SQLAlchemyAccountRepository(AccountRepository):@@ -19,6 +24,14 @@ class SQLAlchemyAccountRepository(AccountRepository):account = session.get(Account, account_id)return self._to_snapshot(account) if account is not None else None+ @override+ def get_credentials(self, account_id: str) -> AccountCredentials | None:+ with self._session_factory() as session:+ account = session.get(Account, account_id)+ if account is None:+ return None+ return AccountCredentials(password_hash=account.password, password_salt=account.password_salt)+@overridedef update_profile(self, account_id: str, changes: AccountProfileChanges) -> AccountSnapshot | None:with self._session_factory.begin() as session:@@ -40,6 +53,18 @@ class SQLAlchemyAccountRepository(AccountRepository):session.flush()return self._to_snapshot(account)+ @override+ def update_password(self, account_id: str, password: AccountPasswordDigest) -> AccountSnapshot | None:+ with self._session_factory.begin() as session:+ account = session.get(Account, account_id)+ if account is None:+ return None++ account.password = password.password_hash+ account.password_salt = password.password_salt+ session.flush()+ return self._to_snapshot(account)+@staticmethoddef _to_snapshot(account: Account) -> AccountSnapshot:return AccountSnapshot(diff --git a/api/services/account_avatar_file_gateway.py b/api/services/account_avatar_file_gateway.pynew file mode 100644index 00000000000..7367d4abdca--- /dev/null+++ b/api/services/account_avatar_file_gateway.py@@ -0,0 +1,33 @@+"""File-domain adapter used by the account avatar application service."""++from typing import override++from sqlalchemy import select+from sqlalchemy.orm import Session, sessionmaker++from graphon.file import helpers as file_helpers+from models.enums import CreatorUserRole+from models.model import UploadFile+from services.account_ports import AccountAvatarFileGateway+++class SQLAlchemyAccountAvatarFileGateway(AccountAvatarFileGateway):+ def __init__(self, *, session_factory: sessionmaker[Session]) -> None:+ self._session_factory = session_factory++ @override+ def get_owned_signed_url(self, *, account_id: str, upload_file_id: str) -> str | None:+ with self._session_factory() as session:+ owned_file_id = session.scalar(+ select(UploadFile.id)+ .where(+ UploadFile.id == upload_file_id,+ UploadFile.created_by_role == CreatorUserRole.ACCOUNT,+ UploadFile.created_by == account_id,+ )+ .limit(1)+ )++ if owned_file_id is None:+ return None+ return file_helpers.get_signed_file_url(upload_file_id=owned_file_id)diff --git a/api/services/account_avatar_service.py b/api/services/account_avatar_service.pynew file mode 100644index 00000000000..d53adf0c8a5--- /dev/null+++ b/api/services/account_avatar_service.py@@ -0,0 +1,19 @@+"""Application service for resolving a current account avatar URL."""++from machinery.context import RequestContext+from services.account_errors import AvatarFileNotFoundError+from services.account_ports import AccountAvatarFileGateway+++class AccountAvatarService:+ def __init__(self, *, files: AccountAvatarFileGateway) -> None:+ self._files = files++ def resolve(self, context: RequestContext, avatar: str) -> str:+ if avatar.startswith(("http://", "https://")):+ return avatar++ avatar_url = self._files.get_owned_signed_url(account_id=context.account_id, upload_file_id=avatar)+ if avatar_url is None:+ raise AvatarFileNotFoundError+ return avatar_urldiff --git a/api/services/account_errors.py b/api/services/account_errors.pyindex 2aba4cd4be7..510155d46af 100644--- a/api/services/account_errors.py+++ b/api/services/account_errors.py@@ -7,3 +7,15 @@ class AccountApplicationError(Exception):class AccountNotFoundError(AccountApplicationError):"""The admitted account no longer exists."""+++class CurrentAccountPasswordIncorrectError(AccountApplicationError):+ """The supplied current password does not match the account credential."""+++class InvalidAccountPasswordError(AccountApplicationError):+ """The requested password does not satisfy the account password policy."""+++class AvatarFileNotFoundError(AccountApplicationError):+ """The requested avatar file does not exist or is not owned by the account."""diff --git a/api/services/account_integration_service.py b/api/services/account_integration_service.pynew file mode 100644index 00000000000..2fc1ebf2a6f--- /dev/null+++ b/api/services/account_integration_service.py@@ -0,0 +1,34 @@+"""Application service for listing current account integrations."""++from collections.abc import Sequence++from machinery.context import RequestContext+from services.account_ports import AccountIntegrationRepository+from services.entities.account_entities import AccountIntegrationStatus+++class AccountIntegrationService:+ def __init__(+ self,+ *,+ integrations: AccountIntegrationRepository,+ providers: Sequence[str] = ("github", "google"),+ ) -> None:+ self._integrations = integrations+ self._providers = tuple(providers)++ def list(self, context: RequestContext) -> list[AccountIntegrationStatus]:+ integrations = self._integrations.list_for_account(context.account_id)++ integrations_by_provider = {integration.provider: integration for integration in integrations}+ statuses: list[AccountIntegrationStatus] = []+ for provider in self._providers:+ integration = integrations_by_provider.get(provider)+ statuses.append(+ AccountIntegrationStatus(+ provider=provider,+ created_at=integration.created_at if integration else None,+ is_bound=integration is not None,+ )+ )+ return statusesdiff --git a/api/services/account_password_hasher.py b/api/services/account_password_hasher.pynew file mode 100644index 00000000000..e53bb05475e--- /dev/null+++ b/api/services/account_password_hasher.py@@ -0,0 +1,28 @@+"""Legacy password implementation behind the account password port."""++import base64+import secrets+from typing import override++from libs.password import compare_password, hash_password, valid_password+from services.account_errors import InvalidAccountPasswordError+from services.account_ports import AccountPasswordHasher+from services.entities.account_entities import AccountPasswordDigest+++class LegacyAccountPasswordHasher(AccountPasswordHasher):+ @override+ def verify(self, password: str, *, password_hash: str, password_salt: str) -> bool:+ return compare_password(password, password_hash, password_salt)++ @override+ def hash(self, password: str) -> AccountPasswordDigest:+ try:+ valid_password(password)+ except ValueError as error:+ raise InvalidAccountPasswordError(str(error)) from error+ salt = secrets.token_bytes(16)+ return AccountPasswordDigest(+ password_hash=base64.b64encode(hash_password(password, salt)).decode(),+ password_salt=base64.b64encode(salt).decode(),+ )diff --git a/api/services/account_password_service.py b/api/services/account_password_service.pynew file mode 100644index 00000000000..b6ef736d293--- /dev/null+++ b/api/services/account_password_service.py@@ -0,0 +1,38 @@+"""Application service for changing a current account password."""++from machinery.context import RequestContext+from services.account_errors import AccountNotFoundError, CurrentAccountPasswordIncorrectError+from services.account_ports import AccountPasswordHasher, AccountRepository+from services.entities.account_entities import AccountSnapshot+++class AccountPasswordService:+ def __init__(+ self,+ *,+ accounts: AccountRepository,+ passwords: AccountPasswordHasher,+ ) -> None:+ self._accounts = accounts+ self._passwords = passwords++ def change(self, context: RequestContext, *, current_password: str, new_password: str) -> AccountSnapshot:+ credentials = self._accounts.get_credentials(context.account_id)+ if credentials is None:+ raise AccountNotFoundError++ if credentials.password_hash and (+ credentials.password_salt is None+ or not self._passwords.verify(+ current_password,+ password_hash=credentials.password_hash,+ password_salt=credentials.password_salt,+ )+ ):+ raise CurrentAccountPasswordIncorrectError++ password = self._passwords.hash(new_password)+ account = self._accounts.update_password(context.account_id, password)+ if account is None:+ raise AccountNotFoundError+ return accountdiff --git a/api/services/account_ports.py b/api/services/account_ports.pyindex 6de05706119..4428b2152d2 100644--- a/api/services/account_ports.py+++ b/api/services/account_ports.py@@ -2,10 +2,34 @@from typing import Protocol-from services.entities.account_entities import AccountProfileChanges, AccountSnapshot+from services.entities.account_entities import (+ AccountCredentials,+ AccountIntegrationSnapshot,+ AccountPasswordDigest,+ AccountProfileChanges,+ AccountSnapshot,+)class AccountRepository(Protocol):def get(self, account_id: str) -> AccountSnapshot | None: ...+ def get_credentials(self, account_id: str) -> AccountCredentials | None: ...+def update_profile(self, account_id: str, changes: AccountProfileChanges) -> AccountSnapshot | None: ...++ def update_password(self, account_id: str, password: AccountPasswordDigest) -> AccountSnapshot | None: ...+++class AccountIntegrationRepository(Protocol):+ def list_for_account(self, account_id: str) -> list[AccountIntegrationSnapshot]: ...+++class AccountAvatarFileGateway(Protocol):+ def get_owned_signed_url(self, *, account_id: str, upload_file_id: str) -> str | None: ...+++class AccountPasswordHasher(Protocol):+ def verify(self, password: str, *, password_hash: str, password_salt: str) -> bool: ...++ def hash(self, password: str) -> AccountPasswordDigest: ...diff --git a/api/services/account_service.py b/api/services/account_service.pyindex 7f669a7ec6b..0a58875288d 100644--- a/api/services/account_service.py+++ b/api/services/account_service.py@@ -66,7 +66,6 @@ from services.errors.account import (AccountPasswordError,AccountRegisterError,CannotOperateSelfError,- CurrentPasswordIncorrectError,EmailDomainSuspendedError,InvalidActionError,LinkAccountIntegrateError,@@ -422,28 +421,6 @@ class AccountService:return account- @staticmethod- def update_account_password(account: Account, password: str, new_password: str, *, session: Session):- """update account password"""- if account.password and not compare_password(password, account.password, account.password_salt):- raise CurrentPasswordIncorrectError("Current password is incorrect.")-- # may be raised- valid_password(new_password)-- # generate password salt- salt = secrets.token_bytes(16)- base64_salt = base64.b64encode(salt).decode()-- # encrypt password with salt- password_hashed = hash_password(new_password, salt)- base64_password_hashed = base64.b64encode(password_hashed).decode()- account.password = base64_password_hashed- account.password_salt = base64_salt- session.add(account)- session.commit()- return account-@staticmethoddef create_account(email: str,diff --git a/api/services/entities/account_entities.py b/api/services/entities/account_entities.pyindex c3244d097a4..dde47283a2d 100644--- a/api/services/entities/account_entities.py+++ b/api/services/entities/account_entities.py@@ -40,3 +40,28 @@ class AccountProfileChanges:self.timezone,))+++@dataclass(frozen=True, slots=True)+class AccountCredentials:+ password_hash: str | None+ password_salt: str | None+++@dataclass(frozen=True, slots=True)+class AccountPasswordDigest:+ password_hash: str+ password_salt: str+++@dataclass(frozen=True, slots=True)+class AccountIntegrationSnapshot:+ provider: str+ created_at: datetime+++@dataclass(frozen=True, slots=True)+class AccountIntegrationStatus:+ provider: str+ created_at: datetime | None+ is_bound: booldiff --git a/api/services/errors/account.py b/api/services/errors/account.pyindex 090ecc373a0..153c3c0674d 100644--- a/api/services/errors/account.py+++ b/api/services/errors/account.py@@ -34,10 +34,6 @@ class AccountNotLinkTenantError(BaseServiceError):pass-class CurrentPasswordIncorrectError(BaseServiceError):- pass--class LinkAccountIntegrateError(BaseServiceError):passdiff --git a/api/tests/test_containers_integration_tests/services/test_account_service.py b/api/tests/test_containers_integration_tests/services/test_account_service.pyindex e6d148c0ffe..4d1cea54668 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@@ -17,7 +17,6 @@ from services.errors.account import (AccountLoginError,AccountPasswordError,AccountRegisterError,- CurrentPasswordIncorrectError,SeatsLimitExceededError,TenantNotFoundError,)@@ -302,96 +301,6 @@ class TestAccountService:assert authenticated_account.status == AccountStatus.ACTIVEassert authenticated_account.initialized_at is not None- def test_update_account_password_success(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test successful password update.- """- fake = Faker()- email = fake.email()- name = fake.name()- old_password = generate_valid_password(fake)- 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["billing_service"].is_email_in_freeze.return_value = False-- # Create account- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=old_password,- session=db_session_with_containers,- )-- # Update password- updated_account = AccountService.update_account_password(- account, old_password, new_password, session=db_session_with_containers- )-- # Verify new password works- authenticated_account = AccountService.authenticate(email, new_password, session=db_session_with_containers)- assert authenticated_account.id == account.id-- def test_update_account_password_wrong_current_password(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test password update with wrong current password.- """- fake = Faker()- email = fake.email()- name = fake.name()- old_password = generate_valid_password(fake)- wrong_password = generate_valid_password(fake)- 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["billing_service"].is_email_in_freeze.return_value = False-- # Create account- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=old_password,- session=db_session_with_containers,- )-- with pytest.raises(CurrentPasswordIncorrectError):- AccountService.update_account_password(- account, wrong_password, new_password, session=db_session_with_containers- )-- def test_update_account_password_invalid_new_password(- self, db_session_with_containers: Session, mock_external_service_dependencies- ):- """- Test password update with invalid new password format.- """- fake = Faker()- email = fake.email()- name = fake.name()- old_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["billing_service"].is_email_in_freeze.return_value = False-- # Create account- account = AccountService.create_account(- email=email,- name=name,- interface_language="en-US",- password=old_password,- session=db_session_with_containers,- )-- # Test with too short password (assuming minimum length validation)- with pytest.raises(ValueError): # Password validation error- AccountService.update_account_password(account, old_password, "123", session=db_session_with_containers)-def test_create_account_and_tenant(self, db_session_with_containers: Session, mock_external_service_dependencies):"""Test account creation with automatic tenant creation.diff --git a/api/tests/unit_tests/controllers/console/workspace/test_accounts.py b/api/tests/unit_tests/controllers/console/workspace/test_accounts.pyindex f0480ea019f..824ecc67f85 100644--- a/api/tests/unit_tests/controllers/console/workspace/test_accounts.py+++ b/api/tests/unit_tests/controllers/console/workspace/test_accounts.py@@ -1,5 +1,5 @@import inspect-from datetime import UTC, datetime+from datetime import datetimefrom types import SimpleNamespacefrom unittest.mock import MagicMock, PropertyMock, patchfrom uuid import NAMESPACE_URL, uuid5@@ -8,7 +8,7 @@ import pytestfrom flask import Flaskfrom jsonschema import Draft202012Validatorfrom sqlalchemy.orm import Session-from werkzeug.exceptions import NotFound+from werkzeug.exceptions import NotFound, UnprocessableEntityfrom controllers.console import console_nsfrom controllers.console.auth.error import (@@ -38,16 +38,18 @@ from controllers.console.workspace.error import (AccountAlreadyInitedError,CurrentPasswordIncorrectError,InvalidAccountDeletionCodeError,+ InvalidAccountPasswordRequestError,)from enums import DeploymentEdition-from extensions.storage.storage_type import StorageTypefrom machinery.context import RequestContext-from models import Account, AccountIntegrate, InvitationCode, Tenant, TenantAccountJoin+from models import Account, InvitationCode, Tenant, TenantAccountJoinfrom models.account import AccountStatus, InvitationCodeStatus, TenantAccountRole-from models.enums import CreatorUserRole-from models.model import UploadFile-from services.entities.account_entities import AccountProfileChanges-from services.errors.account import CurrentPasswordIncorrectError as ServicePwdError+from services.account_errors import (+ AvatarFileNotFoundError,+ CurrentAccountPasswordIncorrectError,+ InvalidAccountPasswordError,+)+from services.entities.account_entities import AccountIntegrationStatus, AccountProfileChangesdef make_account(account_id: str = "u1", *, status: AccountStatus = AccountStatus.ACTIVE) -> Account:@@ -84,22 +86,6 @@ def persist_account_with_tenant(return account, tenant-def make_upload_file(*, tenant_id: str, created_by: str) -> UploadFile:- return UploadFile(- tenant_id=tenant_id,- storage_type=StorageType.LOCAL,- key="avatar.png",- name="avatar.png",- size=128,- extension="png",- mime_type="image/png",- created_by_role=CreatorUserRole.ACCOUNT,- created_by=created_by,- created_at=datetime.now(UTC).replace(tzinfo=None),- used=False,- )--class TestAccountInitApi:@pytest.mark.parametrize("sqlite_session",@@ -159,13 +145,27 @@ class TestAccountProfileApi:def test_get_profile_success(self, app: Flask):api = AccountProfileApi()method = inspect.unwrap(api.get)-user = make_account()+ request_context = RequestContext(+ request_id="request-1",+ trace_id=None,+ account_id=user.id,+ active_workspace_id="workspace-1",+ )+ profile = MagicMock()+ profile.get.return_value = user- with app.test_request_context("/account/profile"):- result = method(api, user)+ with (+ app.test_request_context("/account/profile"),+ patch(+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(profile=profile)),+ ),+ ):+ result = method(api, request_context)assert result["id"] == user.id+ profile.get.assert_called_once_with(request_context)class TestAccountUpdateApis:@@ -313,130 +313,74 @@ class TestAccountProfilePatchApi:class TestAccountAvatarApiGet:- """GET /account/avatar must not sign arbitrary upload_file IDs (IDOR)."""-- @pytest.mark.parametrize(- "sqlite_session",- [(Account, Tenant, TenantAccountJoin, UploadFile)],- indirect=True,- )- def test_get_avatar_signed_url_when_upload_owned_by_current_account(self, app: Flask, sqlite_session: Session):+ def test_get_avatar_delegates_to_service(self, app: Flask):api = AccountAvatarApi()method = inspect.unwrap(api.get)-- user, tenant = persist_account_with_tenant(sqlite_session, "acc-owner")- tenant_id = tenant.idfile_id = "550e8400-e29b-41d4-a716-446655440000"-- upload_file = make_upload_file(tenant_id=tenant_id, created_by=user.id)- upload_file.id = file_id- sqlite_session.add(upload_file)- sqlite_session.commit()+ request_context = RequestContext(+ request_id="request-1",+ trace_id=None,+ account_id="account-1",+ active_workspace_id="workspace-1",+ )+ avatar = MagicMock()+ avatar.resolve.return_value = "https://signed/example"with (app.test_request_context(f"/account/avatar?avatar={file_id}"),- patch("controllers.console.workspace.account.db.session", sqlite_session),patch(- "controllers.console.workspace.account.file_helpers.get_signed_file_url",- return_value="https://signed/example",- ) as sign_mock,+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(avatar=avatar)),+ ),):- result = method(api, AccountAvatarQuery(avatar=file_id), user)+ result = method(api, AccountAvatarQuery(avatar=file_id), request_context)assert result == {"avatar_url": "https://signed/example"}- sign_mock.assert_called_once_with(upload_file_id=file_id)+ avatar.resolve.assert_called_once_with(request_context, file_id)- @pytest.mark.parametrize(- "sqlite_session",- [(Account, Tenant, TenantAccountJoin, UploadFile)],- indirect=True,- )- def test_get_avatar_not_found_when_upload_created_by_other_account_same_tenant(- self, app: Flask, sqlite_session: Session- ):+ def test_get_avatar_maps_not_found(self, app: Flask):api = AccountAvatarApi()method = inspect.unwrap(api.get)-- user, tenant = persist_account_with_tenant(sqlite_session, "acc-a")- tenant_id = tenant.idfile_id = "550e8400-e29b-41d4-a716-446655440001"-- other_account = make_account("acc-b")- other_membership = TenantAccountJoin(- tenant_id=tenant_id,- account_id=other_account.id,- role=TenantAccountRole.NORMAL,+ request_context = RequestContext(+ request_id="request-1",+ trace_id=None,+ account_id="account-1",+ active_workspace_id="workspace-1",)- upload_file = make_upload_file(tenant_id=tenant_id, created_by=other_account.id)- upload_file.id = file_id- sqlite_session.add_all([other_account, other_membership, upload_file])- sqlite_session.commit()+ avatar = MagicMock()+ avatar.resolve.side_effect = AvatarFileNotFoundErrorwith (app.test_request_context(f"/account/avatar?avatar={file_id}"),- patch("controllers.console.workspace.account.db.session", sqlite_session),patch(- "controllers.console.workspace.account.file_helpers.get_signed_file_url",- return_value="https://signed/example",- ) as sign_mock,+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(avatar=avatar)),+ ),):with pytest.raises(NotFound):- method(api, AccountAvatarQuery(avatar=file_id), user)+ method(api, AccountAvatarQuery(avatar=file_id), request_context)- sign_mock.assert_not_called()-- @pytest.mark.parametrize(- "sqlite_session",- [(Account, Tenant, TenantAccountJoin, UploadFile)],- indirect=True,- )- def test_get_avatar_signed_url_when_upload_owned_by_current_account_in_other_tenant(- self, app: Flask, sqlite_session: Session- ):- api = AccountAvatarApi()- method = inspect.unwrap(api.get)-- user, _ = persist_account_with_tenant(sqlite_session, "acc-owner")- file_id = "550e8400-e29b-41d4-a716-446655440002"-- other_tenant = Tenant(name="tenant-other")- other_tenant.id = str(uuid5(NAMESPACE_URL, "tenant:tenant-other"))- upload_file = make_upload_file(tenant_id=other_tenant.id, created_by=user.id)- upload_file.id = file_id- sqlite_session.add_all([other_tenant, upload_file])- sqlite_session.commit()+ def test_get_avatar_missing_query_returns_unprocessable_entity(self, app: Flask):+ account = make_account()with (- app.test_request_context(f"/account/avatar?avatar={file_id}"),- patch("controllers.console.workspace.account.db.session", sqlite_session),+ app.test_request_context("/account/avatar"),+ patch("controllers.console.wraps._is_setup_completed", return_value=True),+ patch("libs.login.dify_config.LOGIN_DISABLED", True),patch(- "controllers.console.workspace.account.file_helpers.get_signed_file_url",- return_value="https://signed/example",- ) as sign_mock,- ):- result = method(api, AccountAvatarQuery(avatar=file_id), user)-- assert result == {"avatar_url": "https://signed/example"}- sign_mock.assert_called_once_with(upload_file_id=file_id)-- def test_get_avatar_https_pass_through_without_signing(self, app: Flask):- api = AccountAvatarApi()- method = inspect.unwrap(api.get)-- user = make_account("acc-owner")- external = "https://cdn.example/avatar.png"-- with (- app.test_request_context(f"/account/avatar?avatar={external}"),+ "controllers.console.wraps.current_account_with_tenant",+ return_value=(account, "workspace-1"),+ ),patch(- "controllers.console.workspace.account.file_helpers.get_signed_file_url",- return_value="https://signed/should-not-use",- ) as sign_mock,+ "controllers.console.flask_admission.current_account_with_tenant",+ return_value=SimpleNamespace(account=account, tenant_id="workspace-1"),+ ),):- result = method(api, AccountAvatarQuery(avatar=external), user)+ with pytest.raises(UnprocessableEntity) as exc_info:+ AccountAvatarApi().get()- assert result == {"avatar_url": external}- sign_mock.assert_not_called()+ assert exc_info.value.code == 422class TestAccountPasswordApi:@@ -451,14 +395,30 @@ class TestAccountPasswordApi:}user = make_account()+ request_context = RequestContext(+ request_id="request-1",+ trace_id=None,+ account_id=user.id,+ active_workspace_id="workspace-1",+ )+ password = MagicMock()+ password.change.return_value = userwith (app.test_request_context("/", json=payload),- patch("controllers.console.workspace.account.AccountService.update_account_password", return_value=None),+ patch(+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(password=password)),+ ),):- result = method(api, user)+ result = method(api, request_context)assert result["id"] == user.id+ password.change.assert_called_once_with(+ request_context,+ current_password="old",+ new_password="new123",+ )def test_password_wrong_current(self, app: Flask):api = AccountPasswordApi()@@ -470,45 +430,87 @@ class TestAccountPasswordApi:"repeat_new_password": "new123",}user = make_account()+ request_context = RequestContext(+ request_id="request-1",+ trace_id=None,+ account_id=user.id,+ active_workspace_id="workspace-1",+ )+ password = MagicMock()+ password.change.side_effect = CurrentAccountPasswordIncorrectErrorwith (app.test_request_context("/", json=payload),patch(- "controllers.console.workspace.account.AccountService.update_account_password",- side_effect=ServicePwdError(),+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(password=password)),),):with pytest.raises(CurrentPasswordIncorrectError):- method(api, user)+ method(api, request_context)++ def test_password_policy_error_is_mapped(self, app: Flask):+ api = AccountPasswordApi()+ method = inspect.unwrap(api.post)+ payload = {+ "password": "old",+ "new_password": "letters-only",+ "repeat_new_password": "letters-only",+ }+ request_context = RequestContext(+ request_id="request-1",+ trace_id=None,+ account_id="account-1",+ active_workspace_id="workspace-1",+ )+ password = MagicMock()+ password.change.side_effect = InvalidAccountPasswordError(+ "Password must contain letters and numbers, and the length must be at least 8 characters."+ )++ with (+ app.test_request_context("/", json=payload),+ patch(+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(password=password)),+ ),+ ):+ with pytest.raises(InvalidAccountPasswordRequestError) as exc_info:+ method(api, request_context)++ assert exc_info.value.data == {+ "code": "invalid_account_password",+ "message": "Password must contain letters and numbers, and the length must be at least 8 characters.",+ "status": 400,+ }class TestAccountIntegrateApi:- @pytest.mark.parametrize(- "sqlite_session",- [(Account, Tenant, TenantAccountJoin, AccountIntegrate)],- indirect=True,- )- def test_get_integrates(self, app: Flask, sqlite_session: Session):+ def test_get_integrates(self, app: Flask):api = AccountIntegrateApi()method = inspect.unwrap(api.get)-- account, _ = persist_account_with_tenant(sqlite_session, "acc1")- sqlite_session.add(- AccountIntegrate(- account_id=account.id,- provider="github",- open_id="github-user",- encrypted_token="encrypted-token",- )+ request_context = RequestContext(+ request_id="request-1",+ trace_id=None,+ account_id="account-1",+ active_workspace_id="workspace-1",)- sqlite_session.commit()+ integrations = MagicMock()+ integrations.list.return_value = [+ AccountIntegrationStatus(provider="github", created_at=datetime(2026, 1, 1), is_bound=True),+ AccountIntegrationStatus(provider="google", created_at=None, is_bound=False),+ ]with (app.test_request_context("/"),- patch("controllers.console.workspace.account.db.session", sqlite_session),+ patch(+ "controllers.console.workspace.account.application_services",+ return_value=SimpleNamespace(accounts=SimpleNamespace(integrations=integrations)),+ ),):- result = method(api, account)+ result = method(api, request_context)+ integrations.list.assert_called_once_with(request_context)assert result["data"][0]["provider"] == "github"assert result["data"][0]["is_bound"] is Trueassert result["data"][0]["link"] is Nonediff --git a/api/tests/unit_tests/extensions/test_ext_application_services.py b/api/tests/unit_tests/extensions/test_ext_application_services.pyindex d727f47221f..d83c62b5435 100644--- a/api/tests/unit_tests/extensions/test_ext_application_services.py+++ b/api/tests/unit_tests/extensions/test_ext_application_services.py@@ -17,6 +17,7 @@ from extensions import ext_application_servicesfrom extensions.ext_redis import RedisClientWrapperfrom models.model import AccountTrialAppRecord, DifySetupfrom repositories.account_activation_repository import SQLAlchemyAccountActivationRepository+from repositories.account_integration_repository import SQLAlchemyAccountIntegrationRepositoryfrom repositories.account_repository import SQLAlchemyAccountRepositoryfrom services import recommended_app_catalog_gatewayfrom services.account_activation_adapters import (@@ -25,6 +26,7 @@ from services.account_activation_adapters import (DeploymentWorkspaceInvitePolicy,RegisterServiceInvitationTokenStore,)+from services.account_avatar_file_gateway import SQLAlchemyAccountAvatarFileGatewayfrom services.auth.data_source_api_key_auth_service import DataSourceApiKeyAuthServicefrom services.enterprise.enterprise_service import WebAppSettingsfrom services.errors.enterprise import EnterpriseAPIError, EnterpriseAPINotFoundError@@ -182,6 +184,13 @@ def test_build_application_services_wires_account_profile_repository(accounts = services.accounts.profile._accountsassert isinstance(accounts, SQLAlchemyAccountRepository)assert accounts._session_factory is sqlite_session_factory+ assert services.accounts.password._accounts is accounts+ integrations = services.accounts.integrations._integrations+ assert isinstance(integrations, SQLAlchemyAccountIntegrationRepository)+ assert integrations._session_factory is sqlite_session_factory+ avatar_files = services.accounts.avatar._files+ assert isinstance(avatar_files, SQLAlchemyAccountAvatarFileGateway)+ assert avatar_files._session_factory is sqlite_session_factory@pytest.mark.parametrize(diff --git a/api/tests/unit_tests/repositories/test_account_repository.py b/api/tests/unit_tests/repositories/test_account_repository.pyindex 60c20e9eef3..96720c2387d 100644--- a/api/tests/unit_tests/repositories/test_account_repository.py+++ b/api/tests/unit_tests/repositories/test_account_repository.py@@ -1,9 +1,10 @@import pytestfrom sqlalchemy.orm import Session, sessionmaker-from models.account import Account+from models.account import Account, AccountIntegrate+from repositories.account_integration_repository import SQLAlchemyAccountIntegrationRepositoryfrom repositories.account_repository import SQLAlchemyAccountRepository-from services.entities.account_entities import AccountProfileChanges+from services.entities.account_entities import AccountPasswordDigest, AccountProfileChangesdef _persist_account(session: Session) -> Account:@@ -70,3 +71,47 @@ def test_update_profile_rolls_back_on_error(persisted = sqlite_session.get(Account, "account-1")assert persisted is not Noneassert persisted.name == "Original"+++def test_account_repository_updates_password(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ _persist_account(sqlite_session)+ repository = SQLAlchemyAccountRepository(sqlite_session_factory)+ digest = AccountPasswordDigest(password_hash="new-hash", password_salt="new-salt")++ credentials = repository.get_credentials("account-1")+ result = repository.update_password("account-1", digest)++ assert credentials is not None+ assert credentials.password_hash is None+ assert result is not None+ assert result.is_password_set is True+ sqlite_session.expire_all()+ persisted = sqlite_session.get(Account, "account-1")+ assert persisted is not None+ assert persisted.password == "new-hash"+ assert persisted.password_salt == "new-salt"+++def test_account_integration_repository_lists_integrations(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ _persist_account(sqlite_session)+ sqlite_session.add(+ AccountIntegrate(+ account_id="account-1",+ provider="github",+ open_id="github-user",+ encrypted_token="encrypted-token",+ )+ )+ sqlite_session.commit()+ repository = SQLAlchemyAccountIntegrationRepository(sqlite_session_factory)++ integrations = repository.list_for_account("account-1")++ assert len(integrations) == 1+ assert integrations[0].provider == "github"diff --git a/api/tests/unit_tests/services/test_account_avatar_file_gateway.py b/api/tests/unit_tests/services/test_account_avatar_file_gateway.pynew file mode 100644index 00000000000..de0f8a9eaed--- /dev/null+++ b/api/tests/unit_tests/services/test_account_avatar_file_gateway.py@@ -0,0 +1,50 @@+from datetime import UTC, datetime+from unittest.mock import patch++from sqlalchemy.orm import Session, sessionmaker++from extensions.storage.storage_type import StorageType+from models.account import Tenant+from models.enums import CreatorUserRole+from models.model import UploadFile+from services.account_avatar_file_gateway import SQLAlchemyAccountAvatarFileGateway+++def _persist_upload_file(session: Session, *, file_id: str, account_id: str) -> None:+ tenant = Tenant(name=f"Tenant {file_id}")+ tenant.id = f"tenant-{file_id}"+ upload_file = UploadFile(+ tenant_id=tenant.id,+ storage_type=StorageType.LOCAL,+ key="avatar.png",+ name="avatar.png",+ size=128,+ extension="png",+ mime_type="image/png",+ created_by_role=CreatorUserRole.ACCOUNT,+ created_by=account_id,+ created_at=datetime.now(UTC).replace(tzinfo=None),+ used=False,+ )+ upload_file.id = file_id+ session.add_all([tenant, upload_file])+ session.commit()+++def test_gateway_signs_only_an_avatar_owned_by_the_account(+ sqlite_session: Session,+ sqlite_session_factory: sessionmaker[Session],+) -> None:+ _persist_upload_file(sqlite_session, file_id="file-1", account_id="account-1")+ gateway = SQLAlchemyAccountAvatarFileGateway(session_factory=sqlite_session_factory)++ with patch(+ "services.account_avatar_file_gateway.file_helpers.get_signed_file_url",+ return_value="https://signed.example/avatar",+ ) as signer:+ owned_url = gateway.get_owned_signed_url(account_id="account-1", upload_file_id="file-1")+ unowned_url = gateway.get_owned_signed_url(account_id="account-2", upload_file_id="file-1")++ assert owned_url == "https://signed.example/avatar"+ assert unowned_url is None+ signer.assert_called_once_with(upload_file_id="file-1")diff --git a/api/tests/unit_tests/services/test_account_avatar_service.py b/api/tests/unit_tests/services/test_account_avatar_service.pynew file mode 100644index 00000000000..9df586e8b2f--- /dev/null+++ b/api/tests/unit_tests/services/test_account_avatar_service.py@@ -0,0 +1,47 @@+from unittest.mock import Mock++import pytest++from machinery.context import RequestContext+from services.account_avatar_service import AccountAvatarService+from services.account_errors import AvatarFileNotFoundError+from services.account_ports import AccountAvatarFileGateway+++def _context() -> RequestContext:+ return RequestContext(+ request_id="request-1",+ trace_id="trace-1",+ account_id="account-1",+ active_workspace_id="workspace-1",+ )+++def test_resolve_passes_through_external_avatar_without_calling_gateway() -> None:+ files = Mock(spec=AccountAvatarFileGateway)+ service = AccountAvatarService(files=files)++ result = service.resolve(_context(), "https://cdn.example/avatar.png")++ assert result == "https://cdn.example/avatar.png"+ files.get_owned_signed_url.assert_not_called()+++def test_resolve_returns_owned_signed_url() -> None:+ files = Mock(spec=AccountAvatarFileGateway)+ files.get_owned_signed_url.return_value = "https://signed.example/avatar"+ service = AccountAvatarService(files=files)++ result = service.resolve(_context(), "file-1")++ assert result == "https://signed.example/avatar"+ files.get_owned_signed_url.assert_called_once_with(account_id="account-1", upload_file_id="file-1")+++def test_resolve_rejects_missing_or_unowned_file() -> None:+ files = Mock(spec=AccountAvatarFileGateway)+ files.get_owned_signed_url.return_value = None+ service = AccountAvatarService(files=files)++ with pytest.raises(AvatarFileNotFoundError):+ service.resolve(_context(), "file-1")diff --git a/api/tests/unit_tests/services/test_account_integration_service.py b/api/tests/unit_tests/services/test_account_integration_service.pynew file mode 100644index 00000000000..a461b020dae--- /dev/null+++ b/api/tests/unit_tests/services/test_account_integration_service.py@@ -0,0 +1,36 @@+from __future__ import annotations++from datetime import datetime+from unittest.mock import Mock++from machinery.context import RequestContext+from services.account_integration_service import AccountIntegrationService+from services.account_ports import AccountIntegrationRepository+from services.entities.account_entities import AccountIntegrationSnapshot+++def test_list_merges_configured_providers_with_persisted_integrations() -> None:+ created_at = datetime(2026, 1, 1)+ integrations = Mock(spec=AccountIntegrationRepository)+ integrations.list_for_account.return_value = [+ AccountIntegrationSnapshot(provider="github", created_at=created_at),+ AccountIntegrationSnapshot(provider="ignored", created_at=created_at),+ ]+ service = AccountIntegrationService(+ integrations=integrations,+ providers=("github", "google"),+ )+ context = RequestContext(+ request_id="request-1",+ trace_id=None,+ account_id="account-1",+ active_workspace_id="workspace-1",+ )++ result = service.list(context)++ assert [(item.provider, item.created_at, item.is_bound) for item in result] == [+ ("github", created_at, True),+ ("google", None, False),+ ]+ integrations.list_for_account.assert_called_once_with("account-1")diff --git a/api/tests/unit_tests/services/test_account_password_hasher.py b/api/tests/unit_tests/services/test_account_password_hasher.pynew file mode 100644index 00000000000..8e56bffc66f--- /dev/null+++ b/api/tests/unit_tests/services/test_account_password_hasher.py@@ -0,0 +1,28 @@+import pytest++from services.account_errors import InvalidAccountPasswordError+from services.account_password_hasher import LegacyAccountPasswordHasher+++def test_hash_produces_a_digest_that_can_be_verified() -> None:+ passwords = LegacyAccountPasswordHasher()++ digest = passwords.hash("password123")++ assert passwords.verify(+ "password123",+ password_hash=digest.password_hash,+ password_salt=digest.password_salt,+ )+ assert not passwords.verify(+ "different123",+ password_hash=digest.password_hash,+ password_salt=digest.password_salt,+ )+++def test_hash_maps_password_policy_validation() -> None:+ passwords = LegacyAccountPasswordHasher()++ with pytest.raises(InvalidAccountPasswordError, match="Password must contain letters and numbers"):+ passwords.hash("letters-only")diff --git a/api/tests/unit_tests/services/test_account_password_service.py b/api/tests/unit_tests/services/test_account_password_service.pynew file mode 100644index 00000000000..d4b9f7c2050--- /dev/null+++ b/api/tests/unit_tests/services/test_account_password_service.py@@ -0,0 +1,101 @@+from __future__ import annotations++from datetime import datetime+from unittest.mock import Mock++import pytest++from machinery.context import RequestContext+from services.account_errors import AccountNotFoundError, CurrentAccountPasswordIncorrectError+from services.account_password_service import AccountPasswordService+from services.account_ports import AccountPasswordHasher, AccountRepository+from services.entities.account_entities import AccountCredentials, AccountPasswordDigest, AccountSnapshot+++def _context() -> RequestContext:+ return RequestContext(+ request_id="request-1",+ trace_id="trace-1",+ account_id="account-1",+ active_workspace_id="workspace-1",+ )+++def _account() -> AccountSnapshot:+ return AccountSnapshot(+ id="account-1",+ name="Account",+ email="[email protected]",+ avatar=None,+ is_password_set=True,+ interface_language="en-US",+ interface_theme="light",+ timezone="UTC",+ last_login_at=None,+ last_login_ip=None,+ status="active",+ initialized_at=None,+ created_at=datetime(2026, 1, 1),+ )+++def test_change_verifies_current_password_and_updates_digest() -> None:+ accounts = Mock(spec=AccountRepository)+ accounts.get_credentials.return_value = AccountCredentials(password_hash="old-hash", password_salt="old-salt")+ accounts.update_password.return_value = _account()+ passwords = Mock(spec=AccountPasswordHasher)+ passwords.verify.return_value = True+ digest = AccountPasswordDigest(password_hash="new-hash", password_salt="new-salt")+ passwords.hash.return_value = digest+ service = AccountPasswordService(accounts=accounts, passwords=passwords)++ result = service.change(_context(), current_password="old-password", new_password="new-password1")++ assert result == _account()+ passwords.verify.assert_called_once_with(+ "old-password",+ password_hash="old-hash",+ password_salt="old-salt",+ )+ passwords.hash.assert_called_once_with("new-password1")+ accounts.update_password.assert_called_once_with("account-1", digest)+++def test_change_rejects_incorrect_current_password_without_hashing_or_update() -> None:+ accounts = Mock(spec=AccountRepository)+ accounts.get_credentials.return_value = AccountCredentials(password_hash="old-hash", password_salt="old-salt")+ passwords = Mock(spec=AccountPasswordHasher)+ passwords.verify.return_value = False+ service = AccountPasswordService(accounts=accounts, passwords=passwords)++ with pytest.raises(CurrentAccountPasswordIncorrectError):+ service.change(_context(), current_password="wrong", new_password="new-password1")++ passwords.hash.assert_not_called()+ accounts.update_password.assert_not_called()+++def test_change_does_not_verify_current_password_when_account_has_no_password() -> None:+ accounts = Mock(spec=AccountRepository)+ accounts.get_credentials.return_value = AccountCredentials(password_hash=None, password_salt=None)+ accounts.update_password.return_value = _account()+ passwords = Mock(spec=AccountPasswordHasher)+ passwords.hash.return_value = AccountPasswordDigest(password_hash="new-hash", password_salt="new-salt")+ service = AccountPasswordService(accounts=accounts, passwords=passwords)++ service.change(_context(), current_password="", new_password="new-password1")++ passwords.verify.assert_not_called()+ accounts.update_password.assert_called_once()+++def test_change_reports_missing_account() -> None:+ accounts = Mock(spec=AccountRepository)+ accounts.get_credentials.return_value = None+ passwords = Mock(spec=AccountPasswordHasher)+ service = AccountPasswordService(accounts=accounts, passwords=passwords)++ with pytest.raises(AccountNotFoundError):+ service.change(_context(), current_password="old", new_password="new-password1")++ passwords.hash.assert_not_called()diff --git a/api/tests/unit_tests/services/test_account_service.py b/api/tests/unit_tests/services/test_account_service.pyindex b79c20400d4..606c23509bb 100644--- a/api/tests/unit_tests/services/test_account_service.py+++ b/api/tests/unit_tests/services/test_account_service.py@@ -28,7 +28,6 @@ from services.errors.account import (AccountLoginError,AccountPasswordError,AccountRegisterError,- CurrentPasswordIncorrectError,EmailDomainSuspendedError,NoPermissionError,)@@ -426,103 +425,6 @@ class TestAccountService:assert persisted_account.last_login_ip == "203.0.113.11"assert persisted_account.last_login_at is not None- # ==================== Password Management Tests ====================-- def test_update_account_password_success(- self,- sqlite_session_factory: sessionmaker[Session],- mock_password_dependencies: _MockDependencies,- ) -> None:- """Test successful password update with correct current password and valid new password."""- with sqlite_session_factory() as service_session:- account = Account(- name="Test User",- email="[email protected]",- password="hashed_password",- password_salt="salt",- )- service_session.add(account)- service_session.commit()- account_id = account.id-- mock_password_dependencies["compare_password"].return_value = True- mock_password_dependencies["valid_password"].return_value = None- mock_password_dependencies["hash_password"].return_value = b"new_hashed_password"-- result = AccountService.update_account_password(- account,- "old_password",- "new_password123",- session=service_session,- )- assert result is account-- mock_password_dependencies["compare_password"].assert_called_once_with(- "old_password", "hashed_password", "salt"- )- mock_password_dependencies["valid_password"].assert_called_once_with("new_password123")-- with sqlite_session_factory() as assertion_session:- persisted_account = assertion_session.get(Account, account_id)- assert persisted_account is not None- assert persisted_account.password is not None- assert persisted_account.password != "hashed_password"- assert persisted_account.password_salt is not None- assert persisted_account.password_salt != "salt"-- def test_update_account_password_current_password_incorrect(- self, unbound_session: Session, mock_password_dependencies: _MockDependencies- ) -> None:- """Test password update with incorrect current password."""- # Setup test data- mock_account = Account(- name="Test User",- email="[email protected]",- password="hashed_password",- password_salt="salt",- )- mock_password_dependencies["compare_password"].return_value = False-- # Execute test and verify exception- with pytest.raises(CurrentPasswordIncorrectError):- AccountService.update_account_password(- mock_account,- "wrong_password",- "new_password123",- session=unbound_session,- )-- # Verify password comparison was called- mock_password_dependencies["compare_password"].assert_called_once_with(- "wrong_password", "hashed_password", "salt"- )-- def test_update_account_password_invalid_new_password(- self, unbound_session: Session, mock_password_dependencies: _MockDependencies- ) -> None:- """Test password update with invalid new password."""- # Setup test data- mock_account = Account(- name="Test User",- email="[email protected]",- password="hashed_password",- password_salt="salt",- )- mock_password_dependencies["compare_password"].return_value = True- mock_password_dependencies["valid_password"].side_effect = ValueError("Password too short")-- # Execute test and verify exception- with pytest.raises(ValueError):- AccountService.update_account_password(- mock_account,- "old_password",- "short",- session=unbound_session,- )-- # Verify password validation was called- mock_password_dependencies["valid_password"].assert_called_once_with("short")-# ==================== User Loading Tests ====================def test_load_user_success(self, sqlite_session: Session) -> None: