diff --git a/apps/chat/serializers/chat_user_serializer.py b/apps/chat/serializers/chat_user_serializer.py index 1771705769b..db9c74d4dc4 100644 --- a/apps/chat/serializers/chat_user_serializer.py +++ b/apps/chat/serializers/chat_user_serializer.py @@ -138,7 +138,7 @@ def local_login(cls, instance, access_token=None): user = ChatUser.objects.filter(username=username).first() - if not user or not password_verify(password, user.password): + if not user or str(user.source).upper() != "LOCAL" or not password_verify(password, user.password): cls._handle_failed_login(scope, username, failed_attempts, lock_time) raise AppApiException(500, _("The username or password is incorrect")) diff --git a/apps/chat/views/v2/chat.py b/apps/chat/views/v2/chat.py index 40ab0ef1c95..a20eea1049f 100644 --- a/apps/chat/views/v2/chat.py +++ b/apps/chat/views/v2/chat.py @@ -406,7 +406,7 @@ def post(self, request: Request): except Exception: raise AppApiException(500, _("Invalid encrypted data")) serializer_obj = RePasswordSerializer(data=request_data) - if serializer_obj.reset_password(request.user.id): + if serializer_obj.reset_password(request.user.id, request.user.kwargs.get("source")): version, get_key = Cache_Version.CHAT_USER_TOKEN.value auth = request.META.get("HTTP_AUTHORIZATION") cache.delete(get_key(token=auth), version=version) @@ -426,7 +426,12 @@ class ChatUserProfileView(APIView): responses=UserProfileAPI.get_response(), ) def get(self, request: Request): - return result.success(ChatUserProfileSerializer().profile(request.user)) + return result.success( + ChatUserProfileSerializer().profile( + request.user.profile, + source=request.user.kwargs.get("source"), + ) + ) class Logout(APIView): diff --git a/apps/chat/views/v3/chat.py b/apps/chat/views/v3/chat.py index 752153022b8..64f653b4643 100644 --- a/apps/chat/views/v3/chat.py +++ b/apps/chat/views/v3/chat.py @@ -439,7 +439,7 @@ def post(self, request: Request): except Exception: raise AppApiException(500, _("Invalid encrypted data")) serializer_obj = RePasswordSerializer(data=request_data) - if serializer_obj.reset_password(request.user.id): + if serializer_obj.reset_password(request.user.id, request.user.kwargs.get("source")): version, get_key = Cache_Version.CHAT_USER_TOKEN.value auth = request.META.get("HTTP_AUTHORIZATION") cache.delete(get_key(token=auth), version=version) @@ -465,7 +465,12 @@ class ChatUserProfileView(APIView): }, ) def get(self, request: Request): - return result.success(ChatUserProfileSerializer().profile(request.user.profile)) + return result.success( + ChatUserProfileSerializer().profile( + request.user.profile, + source=request.user.kwargs.get("source"), + ) + ) class ChatUserLanguageView(APIView): @@ -574,7 +579,6 @@ class LocalLoginView(BaseAuthView): def post(self, request: Request): access_token = request.query_params.get("accessToken") user = ChatUserAccessTokenV3Serializer.local_login(request.data, access_token) - user.source = "LOCAL" token = self.create_token_and_cache(user, access_token, Operate.LOCAL) response = result.success({"token": token}) return self.generate(request, token, response, path=get_chat_user_cookie_path(access_token)) diff --git a/apps/common/auth/common.py b/apps/common/auth/common.py index c05bf64c154..23946b315b4 100644 --- a/apps/common/auth/common.py +++ b/apps/common/auth/common.py @@ -29,40 +29,42 @@ def get_key(): class SystemToken: - def __init__(self, user_id, _type: AuthenticationType, **kwargs): + def __init__(self, user_id, _type: AuthenticationType, source=None, **kwargs): self.id = user_id self.type = _type + self.source = source self.kwargs = kwargs def to_dict(self): + details = {"id": str(self.id), "type": str(self.type.value)} + if self.source: + details["source"] = str(self.source) if self.kwargs: - return {"user_id": self.id, "type": str(self.type.value), "kwargs": self.kwargs} - return {"id": str(self.id), "type": str(self.type.value)} + details["kwargs"] = self.kwargs + return details def to_token(self): return signing.dumps(self.to_dict(), key=get_key()) class ChatToken: - def __init__(self, user_id, _type: AuthenticationType, login_type: str, **kwargs): + def __init__(self, user_id, _type: AuthenticationType, login_type: str, source=None, **kwargs): self.id = user_id self.type = _type self.login_type = login_type + self.source = source or login_type self.kwargs = kwargs def to_dict(self): - if self.kwargs: - return { - "id": str(self.id), - "type": str(self.type.value), - "login_type": str(self.login_type), - "kwargs": self.kwargs, - } - return { + details = { "id": str(self.id), "type": str(self.type.value), "login_type": str(self.login_type), + "source": str(self.source), } + if self.kwargs: + details["kwargs"] = self.kwargs + return details def to_token(self): return signing.dumps(self.to_dict(), key=get_key()) @@ -73,6 +75,17 @@ def parse_token(token): _type = details.get("type") if _type: if _type == AuthenticationType.SYSTEM_USER.value: - return SystemToken(details.get("id"), details.get("type"), **details.get("kwargs", {})) - return ChatToken(details.get("id"), details.get("type"), details.get("login_type"), **details.get("kwargs", {})) + return SystemToken( + details.get("id") or details.get("user_id"), + details.get("type"), + source=details.get("source"), + **details.get("kwargs", {}), + ) + return ChatToken( + details.get("id"), + details.get("type"), + details.get("login_type"), + source=details.get("source"), + **details.get("kwargs", {}), + ) raise AppAuthenticationFailed(1001, "") diff --git a/apps/common/auth/handle/impl/chat_user_token.py b/apps/common/auth/handle/impl/chat_user_token.py index 3ddf7f36d58..e203e60082d 100644 --- a/apps/common/auth/handle/impl/chat_user_token.py +++ b/apps/common/auth/handle/impl/chat_user_token.py @@ -112,6 +112,7 @@ def support(self, request, token: str, get_token_details): def handle(self, request, token: str, get_token_details): auth_details = get_token_details() login_type = auth_details.get("login_type") + source = auth_details.get("source") or login_type user_id = auth_details.get("id") application_id = (auth_details.get("kwargs") or {}).get("application_id") _type = ( @@ -124,5 +125,5 @@ def handle(self, request, token: str, get_token_details): # 避免返回一个空权限的 Principal 造成静默失败。 if not auth.permissions.get(f"{Group.CHAT_USER}:r:{application_id}"): raise AppUnauthorizedFailed(403, _("No permission to access")) - return Principal(user_id, _type, application_id=application_id, profile=chat_user), auth - return Principal(user_id, _type, profile=chat_user), auth + return Principal(user_id, _type, application_id=application_id, profile=chat_user, source=source), auth + return Principal(user_id, _type, profile=chat_user, source=source), auth diff --git a/apps/common/auth/handle/impl/user_token.py b/apps/common/auth/handle/impl/user_token.py index bbe9b9d17d5..0bf4d8c8caf 100644 --- a/apps/common/auth/handle/impl/user_token.py +++ b/apps/common/auth/handle/impl/user_token.py @@ -299,4 +299,5 @@ def handle(self, request, token: str, get_token_details): if not user.is_active or user.password != cache_token.password: raise AppAuthenticationFailed(1002, _("Authentication information is incorrect")) auth = get_auth(user) - return Principal(user.id, UserType.SYSTEM_USER, user), auth + source = auth_details.get("source") or user.source + return Principal(user.id, UserType.SYSTEM_USER, user, source=source), auth diff --git a/apps/common/tests/test_auth_common.py b/apps/common/tests/test_auth_common.py new file mode 100644 index 00000000000..47f6d22488d --- /dev/null +++ b/apps/common/tests/test_auth_common.py @@ -0,0 +1,80 @@ +from types import SimpleNamespace +from unittest.mock import patch + +from django.core import signing +from django.test import SimpleTestCase + +from common.auth.common import ChatToken, SystemToken, parse_token +from common.auth.handle.impl import chat_user_token, user_token +from common.auth.handle.impl.chat_user_token import ChatUserToken +from common.auth.handle.impl.user_token import UserToken +from common.auth.struct.auth import Auth +from common.constants.authentication_type import AuthenticationType + + +class TokenSourceTests(SimpleTestCase): + def test_token_source_survives_encoding_and_parsing(self): + with patch("common.auth.common.get_key", return_value="test-signing-key"): + system_details = signing.loads( + SystemToken("system-user", AuthenticationType.SYSTEM_USER, source="OIDC").to_token(), + key="test-signing-key", + ) + system_token = parse_token( + SystemToken("system-user", AuthenticationType.SYSTEM_USER, source="OIDC").to_token() + ) + chat_details = signing.loads( + ChatToken("chat-user", AuthenticationType.CHAT_USER, "LOCAL", source="OIDC").to_token(), + key="test-signing-key", + ) + chat_token = parse_token( + ChatToken("chat-user", AuthenticationType.CHAT_USER, "LOCAL", source="OIDC").to_token() + ) + + self.assertEqual(system_details["source"], "OIDC") + self.assertEqual(system_token.source, "OIDC") + self.assertEqual(chat_details["source"], "OIDC") + self.assertEqual(chat_token.source, "OIDC") + + +class TokenHandlerSourceTests(SimpleTestCase): + def test_system_token_handler_exposes_login_source(self): + user = SimpleNamespace(id="system-user", is_active=True, password="password-hash", source="LOCAL") + + def token_details(): + return { + "id": "system-user", + "type": AuthenticationType.SYSTEM_USER.value, + "source": "OIDC", + } + + with ( + patch.object(user_token, "cache") as token_cache, + patch.object(user_token, "QuerySet") as query_set, + patch.object(user_token, "get_auth", return_value=Auth(set(), {})), + patch.object(user_token.CONFIG, "get_session_timeout", return_value=3600), + ): + token_cache.get.return_value = SimpleNamespace(password="password-hash") + query_set.return_value.get.return_value = user + principal, _ = UserToken().handle(None, "token", token_details) + + self.assertEqual(principal.kwargs["source"], "OIDC") + + def test_chat_token_handler_exposes_login_source(self): + user = SimpleNamespace(id="chat-user", source="LOCAL") + + def token_details(): + return { + "id": "chat-user", + "type": AuthenticationType.CHAT_USER.value, + "login_type": "LOCAL", + "source": "OIDC", + } + + with ( + patch.object(chat_user_token, "QuerySet") as query_set, + patch.object(chat_user_token, "get_auth", return_value=Auth(set(), {})), + ): + query_set.return_value.filter.return_value.first.return_value = user + principal, _ = ChatUserToken().handle(None, "token", token_details) + + self.assertEqual(principal.kwargs["source"], "OIDC") diff --git a/apps/system_manage/serializers/chat_user.py b/apps/system_manage/serializers/chat_user.py index 89c2febeabc..9e04bed03a5 100644 --- a/apps/system_manage/serializers/chat_user.py +++ b/apps/system_manage/serializers/chat_user.py @@ -25,11 +25,20 @@ from maxkb.const import CONFIG from system_manage.models import ChatUser, UserGroup, UserGroupRelation from system_manage.models.chat_user_token_quota import ChatUserTokenQuota, QuotaType -from users.serializers.user import PASSWORD_REGEX +from users.serializers.user import PASSWORD_REGEX, _is_default_password application_third_party_version, application_third_party_get_key = Cache_Version.APPLICATION_THIRD_PARTY.value +def _is_local_source(source): + return str(source or "").upper() == "LOCAL" + + +def _ensure_local_chat_user(user, source=None): + if not user or not _is_local_source(user.source) or (source is not None and not _is_local_source(source)): + raise AppApiException(1005, _("Third-party users cannot change passwords")) + + def clear_application_third_party_chat_user_cache(usernames): cache_keys = [application_third_party_get_key(f"chat_user_{username}") for username in usernames] if cache_keys: @@ -433,6 +442,7 @@ def re_password(self, instance, with_valid=True): raise AppApiException(500, _("Invalid encrypted data")) ChatUserSerializer.RePasswordInstance(data=instance).is_valid(raise_exception=True) user = ChatUser.objects.filter(id=self.data.get("id")).first() + _ensure_local_chat_user(user) user.password = password_encrypt(instance.get("password")) user.save() return True @@ -677,11 +687,12 @@ def is_valid(self, *, raise_exception=False): ) return True - def reset_password(self, user_id): + def reset_password(self, user_id, source=None): """ 修改密码 :return: 是否成功 """ + _ensure_local_chat_user(ChatUser.objects.filter(id=user_id).first(), source) if self.is_valid(): QuerySet(ChatUser).filter(id=user_id).update(password=password_encrypt(self.data.get("password"))) return True @@ -689,7 +700,7 @@ def reset_password(self, user_id): class ChatUserProfileSerializer(serializers.Serializer): @staticmethod - def profile(user: ChatUser): + def profile(user: ChatUser, source=None): """ 获取对话用户详情 @param user: 用户对象 @@ -697,6 +708,7 @@ def profile(user: ChatUser): """ if not user: return {} + login_source = source or user.source license_is_valid = DatabaseModelManage.get_model("license_is_valid") or (lambda: False) license_is_valid = license_is_valid() if license_is_valid() is not None else False token_quota = None @@ -716,8 +728,11 @@ def profile(user: ChatUser): "nick_name": user.nick_name, "email": user.email, "language": user.language, - "source": user.source, + "source": login_source, "token_quota": token_quota, + "is_edit_password": _is_default_password(CONFIG.get("DEFAULT_PASSWORD", "MaxKB@123.."), user.password) + if str(login_source or "").upper() == "LOCAL" + else False, } diff --git a/apps/system_manage/tests.py b/apps/system_manage/tests.py index 07f37bb4d61..f55f3aa2d7a 100644 --- a/apps/system_manage/tests.py +++ b/apps/system_manage/tests.py @@ -14,13 +14,19 @@ from common.constants.authentication_type import UserType from common.constants.cache_version import Cache_Version from common.database_model_manage.database_model_manage import DatabaseModelManage -from common.exception.app_exception import AppUnauthorizedFailed +from common.exception.app_exception import AppApiException, AppUnauthorizedFailed +from common.utils.common import password_encrypt +from chat.serializers.chat_user_serializer import ChatUserAccessTokenV3Serializer from role_setting.models import RolePermission, RoleSetting, UserRoleRelation from system_manage.models import ChatUser, UserGroup, UserGroupRelation from system_manage.models.log_management import Log from system_manage.serializers import user_group_resource_permission as user_group_resource_permission_serializer from system_manage.serializers import user_resource_permission as user_resource_permission_serializer -from system_manage.serializers.chat_user import ChatUserSerializer +from system_manage.serializers.chat_user import ( + ChatUserProfileSerializer, + ChatUserSerializer, + RePasswordSerializer as ChatUserRePasswordSerializer, +) from system_manage.views import ( resource_chat_user_group, user_group_resource_permission, @@ -708,6 +714,92 @@ def test_status_and_password_changes_preserve_user_groups(self): self.assertTrue(UserGroupRelation.objects.filter(user=user, group=group).exists()) +class ThirdPartyChatUserPasswordTests(TestCase): + def setUp(self): + self.password = "Password1!" + self.encrypted_password = password_encrypt(self.password) + self.user = ChatUser.objects.create( + username="third-party-chat-user", + nick_name="Third Party Chat User", + email="third-party-chat-user@example.com", + password=self.encrypted_password, + source="lark", + ) + + def test_chat_user_management_password_change_rejects_third_party_user(self): + operate = ChatUserSerializer.Operate(data={"id": self.user.id}) + + with self.assertRaises(AppApiException): + operate.re_password({"password": "Password2!", "re_password": "Password2!"}, with_valid=True) + + self.user.refresh_from_db() + self.assertEqual(self.user.password, self.encrypted_password) + + def test_current_chat_user_password_change_rejects_third_party_user(self): + serializer = ChatUserRePasswordSerializer(data={"password": "Password2!", "re_password": "Password2!"}) + + with self.assertRaises(AppApiException): + serializer.reset_password(self.user.id) + + self.user.refresh_from_db() + self.assertEqual(self.user.password, self.encrypted_password) + + def test_chat_user_local_login_rejects_third_party_user(self): + with patch.object( + ChatUserAccessTokenV3Serializer, + "_get_login_policy", + return_value=("chat-user", -1, 5, 10), + ): + with self.assertRaises(AppApiException): + ChatUserAccessTokenV3Serializer.local_login( + {"username": self.user.username, "password": self.password}, + access_token=None, + ) + + def test_current_chat_user_password_change_rejects_local_session_for_third_party_user(self): + serializer = ChatUserRePasswordSerializer(data={"password": "Password2!", "re_password": "Password2!"}) + + with self.assertRaises(AppApiException): + serializer.reset_password(self.user.id, source="LOCAL") + + self.user.refresh_from_db() + self.assertEqual(self.user.password, self.encrypted_password) + + def test_chat_user_profile_does_not_mask_third_party_source_with_local_login(self): + with patch("system_manage.serializers.chat_user.DatabaseModelManage.get_model", return_value=None): + profile = ChatUserProfileSerializer().profile(self.user, source="LOCAL") + + self.assertEqual(profile["source"], "lark") + + +class EffectiveChatUserLoginSourceTests(TestCase): + def setUp(self): + self.password = "Password1!" + self.encrypted_password = password_encrypt(self.password) + self.user = ChatUser.objects.create( + username="local-chat-user-with-sso-session", + nick_name="Local Chat User", + email="local-chat-user-with-sso-session@example.com", + password=self.encrypted_password, + source="LOCAL", + ) + + def test_chat_user_profile_uses_login_source(self): + with patch("system_manage.serializers.chat_user.DatabaseModelManage.get_model", return_value=None): + profile = ChatUserProfileSerializer().profile(self.user, source="OIDC") + + self.assertEqual(profile["source"], "OIDC") + + def test_current_chat_user_password_change_rejects_third_party_login_source(self): + serializer = ChatUserRePasswordSerializer(data={"password": "Password2!", "re_password": "Password2!"}) + + with self.assertRaises(AppApiException): + serializer.reset_password(self.user.id, source="OIDC") + + self.user.refresh_from_db() + self.assertEqual(self.user.password, self.encrypted_password) + + class ChatUserDeleteTests(TestCase): def setUp(self): self.version, self.get_key = Cache_Version.APPLICATION_THIRD_PARTY.value diff --git a/apps/users/serializers/login.py b/apps/users/serializers/login.py index e973b4df784..ee0ca35b43b 100644 --- a/apps/users/serializers/login.py +++ b/apps/users/serializers/login.py @@ -21,7 +21,6 @@ from common.utils.common import get_random_chars, needs_password_upgrade, password_encrypt, password_verify from common.utils.logger import maxkb_logger from common.utils.rsa_util import decrypt -from django.core import signing from django.core.cache import cache from django.utils.translation import gettext_lazy as _ from maxkb.const import CONFIG @@ -106,7 +105,7 @@ def _decrypt_request_data(instance: dict) -> dict: def _authenticate(username: str, password: str) -> User | None: """校验用户名密码,失败记录计数并抛异常""" user = User.objects.filter(username=username).first() - if not user or not password_verify(password, user.password): + if not user or str(user.source).upper() != "LOCAL" or not password_verify(password, user.password): return None # Transparently upgrade legacy MD5 hash to PBKDF2 @@ -118,7 +117,7 @@ def _authenticate(username: str, password: str) -> User | None: @staticmethod def _issue_token(user: User) -> str: """签发登录 token 并写入缓存""" - token = SystemToken(str(user.id), AuthenticationType.SYSTEM_USER).to_token() + token = SystemToken(str(user.id), AuthenticationType.SYSTEM_USER, source="LOCAL").to_token() version, get_key = Cache_Version.TOKEN.value cache.set(get_key(token), user, timeout=CONFIG.get_session_timeout(), version=version) return token diff --git a/apps/users/serializers/user.py b/apps/users/serializers/user.py index e540a3f6a6e..146c471087d 100644 --- a/apps/users/serializers/user.py +++ b/apps/users/serializers/user.py @@ -66,6 +66,15 @@ DEFAULT_PASSWORD_CHECK_CACHE_TIMEOUT = 7 * 24 * 60 * 60 +def _is_local_source(source): + return str(source or "").upper() == "LOCAL" + + +def _ensure_local_user(user, source=None): + if not user or not _is_local_source(user.source) or (source is not None and not _is_local_source(source)): + raise AppApiException(1005, _("Third-party users cannot change passwords")) + + def _raise_verify_code_limit(): raise AppApiException(500, _("Too many verification code attempts, please try again later")) @@ -283,7 +292,7 @@ def _is_default_password(default_password: str, hashed_password: str): class UserProfileSerializer(serializers.Serializer): @staticmethod - def profile(user: User, auth: Auth): + def profile(user: User, auth: Auth, source=None): """ 获取用户详情 @param user: 用户对象 @@ -304,16 +313,18 @@ def profile(user: User, auth: Auth): role_name = [role.role_name for role in roles] role_info = [{"role_id": str(role.id), "role_name": role.role_name} for role in roles] + login_source = source or user.source + can_change_password = _is_local_source(login_source) return { "id": user.id, "username": user.username, "nick_name": user.nick_name, "email": user.email, - "source": user.source, + "source": login_source, "role": list(auth.roles), "permissions": {k: format(v, "x") for k, v in auth.permissions.items()}, "is_edit_password": _is_default_password(CONFIG.get("DEFAULT_PASSWORD", "MaxKB@123.."), user.password) - if user.source == "LOCAL" + if can_change_password else False, "language": user.language, "workspace_list": workspace_list, @@ -766,6 +777,7 @@ def re_password(self, instance, with_valid=True): raise AppApiException(500, _("Invalid encrypted data")) UserManageSerializer.RePasswordInstance(data=instance).is_valid(raise_exception=True) user = User.objects.filter(id=self.data.get("id")).first() + _ensure_local_user(user) user.password = password_encrypt(instance.get("password")) user.save() return True @@ -1025,6 +1037,7 @@ def reset_password(self): """ if self.is_valid(): email = self.data.get("email") + _ensure_local_user(User.objects.filter(email=email).first()) QuerySet(User).filter(email=email).update(password=password_encrypt(self.data.get("password"))) code_cache_key = email + ":reset_password" cache.delete(get_key(code_cache_key), version=version) @@ -1072,11 +1085,12 @@ def is_valid(self, *, raise_exception=False): ) return True - def reset_password(self, user_id: str): + def reset_password(self, user_id: str, source=None): """ 修改密码 :return: 是否成功 """ + _ensure_local_user(User.objects.filter(id=user_id).first(), source) if self.is_valid(): QuerySet(User).filter(id=user_id).update(password=password_encrypt(self.data.get("password"))) return True diff --git a/apps/users/tests/test_profile.py b/apps/users/tests/test_profile.py index 011220db30d..bd042f97300 100644 --- a/apps/users/tests/test_profile.py +++ b/apps/users/tests/test_profile.py @@ -32,12 +32,12 @@ def setUp(self): ) self.auth = Auth(roles=set(), permissions={}) - def _profile(self): + def _profile(self, source=None): with ( patch("users.serializers.user.DatabaseModelManage.get_model", return_value=None), patch("users.serializers.user.get_workspace_list_by_user", return_value=[]), ): - return UserProfileSerializer().profile(self.user, self.auth) + return UserProfileSerializer().profile(self.user, self.auth, source=source) def test_profile_caches_default_password_check_for_same_hash(self): with patch("users.serializers.user.password_verify", return_value=True) as verify_password: @@ -57,3 +57,17 @@ def test_profile_rechecks_when_password_hash_changes(self): self.assertTrue(first["is_edit_password"]) self.assertFalse(second["is_edit_password"]) self.assertEqual(verify_password.call_count, 2) + + def test_profile_uses_login_source_for_password_visibility(self): + profile = self._profile(source="OIDC") + + self.assertEqual(profile["source"], "OIDC") + self.assertFalse(profile["is_edit_password"]) + + def test_profile_does_not_mask_third_party_source_with_local_login(self): + self.user.source = "lark" + + profile = self._profile(source="LOCAL") + + self.assertEqual(profile["source"], "lark") + self.assertFalse(profile["is_edit_password"]) diff --git a/apps/users/tests/test_user_management.py b/apps/users/tests/test_user_management.py index a340a30c18a..793cc7f4b9f 100644 --- a/apps/users/tests/test_user_management.py +++ b/apps/users/tests/test_user_management.py @@ -1,8 +1,15 @@ -from django.test import TestCase +from types import SimpleNamespace +from unittest.mock import patch +from django.core import signing +from django.test import SimpleTestCase, TestCase + +from common.exception.app_exception import AppApiException +from common.utils.common import password_encrypt, password_verify from users.models import User from users.models.user_group import SystemUserGroup, SystemUserGroupRelation -from users.serializers.user import UserManageSerializer +from users.serializers.login import LoginSerializer +from users.serializers.user import RePasswordSerializer, ResetCurrentUserPassword, UserManageSerializer class UserManagementGroupPreservationTests(TestCase): @@ -23,3 +30,118 @@ def test_status_and_password_changes_preserve_user_groups(self): operate.re_password({"password": "Password1!", "re_password": "Password1!"}, with_valid=True) self.assertTrue(SystemUserGroupRelation.objects.filter(user=user, group=group).exists()) + + +class ThirdPartyUserPasswordTests(TestCase): + def setUp(self): + self.password = "Password1!" + self.encrypted_password = password_encrypt(self.password) + self.user = User.objects.create( + username="third-party-user", + nick_name="Third Party User", + email="third-party-user@example.com", + password=self.encrypted_password, + role="USER", + source="lark", + ) + + def test_user_management_password_change_rejects_third_party_user(self): + operate = UserManageSerializer.Operate(data={"id": self.user.id}) + + with self.assertRaises(AppApiException): + operate.re_password({"password": "Password2!", "re_password": "Password2!"}, with_valid=True) + + self.user.refresh_from_db() + self.assertEqual(self.user.password, self.encrypted_password) + + def test_current_user_password_change_rejects_third_party_user(self): + serializer = ResetCurrentUserPassword(data={"password": "Password2!", "re_password": "Password2!"}) + + with self.assertRaises(AppApiException): + serializer.reset_password(self.user.id) + + self.user.refresh_from_db() + self.assertEqual(self.user.password, self.encrypted_password) + + def test_email_password_reset_rejects_third_party_user(self): + serializer = RePasswordSerializer( + data={ + "email": self.user.email, + "code": "123456", + "password": "Password2!", + "re_password": "Password2!", + } + ) + + with patch("users.serializers.user.check_verify_code_attempts", return_value=True): + with self.assertRaises(AppApiException): + serializer.reset_password() + + self.user.refresh_from_db() + self.assertEqual(self.user.password, self.encrypted_password) + + def test_account_login_rejects_third_party_user(self): + with ( + patch.object(LoginSerializer, "get_auth_setting", return_value={}), + patch("users.serializers.login.DatabaseModelManage.get_model", return_value=lambda: False), + patch.object(LoginSerializer, "_is_account_locked", return_value=False), + patch.object(LoginSerializer, "_need_captcha", return_value=False), + patch.object(LoginSerializer, "_issue_token", return_value="token"), + ): + with self.assertRaises(AppApiException): + LoginSerializer.login({"username": self.user.username, "password": self.password}) + + def test_current_user_password_change_rejects_local_session_for_third_party_user(self): + serializer = ResetCurrentUserPassword(data={"password": "Password2!", "re_password": "Password2!"}) + + with self.assertRaises(AppApiException): + serializer.reset_password(self.user.id, source="LOCAL") + + self.user.refresh_from_db() + self.assertEqual(self.user.password, self.encrypted_password) + + def test_current_user_password_change_rejects_third_party_login_source(self): + local_user = User.objects.create( + username="local-user-with-sso-session", + nick_name="Local User", + email="local-user-with-sso-session@example.com", + password=self.encrypted_password, + role="USER", + source="LOCAL", + ) + serializer = ResetCurrentUserPassword(data={"password": "Password2!", "re_password": "Password2!"}) + + with self.assertRaises(AppApiException): + serializer.reset_password(local_user.id, source="OIDC") + + local_user.refresh_from_db() + self.assertEqual(local_user.password, self.encrypted_password) + + def test_current_user_password_change_accepts_local_source_case_insensitively(self): + local_user = User.objects.create( + username="local-case-insensitive-user", + nick_name="Local User", + email="local-case-insensitive-user@example.com", + password=self.encrypted_password, + role="USER", + source="LOCAL", + ) + serializer = ResetCurrentUserPassword(data={"password": "Password2!", "re_password": "Password2!"}) + + serializer.reset_password(local_user.id, source="local") + + local_user.refresh_from_db() + self.assertTrue(password_verify("Password2!", local_user.password)) + + +class LoginTokenSourceTests(SimpleTestCase): + def test_local_login_token_records_local_source(self): + with ( + patch("users.serializers.login.cache.set"), + patch("users.serializers.login.CONFIG.get_session_timeout", return_value=3600), + patch("common.auth.common.get_key", return_value="test-signing-key"), + ): + token = LoginSerializer._issue_token(SimpleNamespace(id="user-id")) + + details = signing.loads(token, key="test-signing-key") + self.assertEqual(details["source"], "LOCAL") diff --git a/apps/users/views/user.py b/apps/users/views/user.py index 9a053edeeb7..e0dfca2d7c1 100644 --- a/apps/users/views/user.py +++ b/apps/users/views/user.py @@ -86,7 +86,11 @@ class UserProfileView(APIView): responses=UserProfileAPI.get_response(), ) def get(self, request: Request): - return result.success(UserProfileSerializer().profile(request.user.profile, request.auth)) + return result.success( + UserProfileSerializer().profile( + request.user.profile, request.auth, source=request.user.kwargs.get("source") + ) + ) class TestPermissionsUserView(APIView): @@ -102,7 +106,11 @@ class TestPermissionsUserView(APIView): ) @has_permissions(PermissionConstants.USER_EDIT, RoleConstants.ADMIN) def get(self, request: Request): - return result.success(UserProfileSerializer().profile(request.user.profile, request.auth)) + return result.success( + UserProfileSerializer().profile( + request.user.profile, request.auth, source=request.user.kwargs.get("source") + ) + ) class SwitchUserLanguageView(APIView): @@ -139,7 +147,11 @@ class TestWorkspacePermissionUserView(APIView): ) @has_permissions(PermissionConstants.USER_EDIT.get_workspace_permission(), RoleConstants.ADMIN) def get(self, request: Request, workspace_id): - return result.success(UserProfileSerializer().profile(request.user.profile, request.auth)) + return result.success( + UserProfileSerializer().profile( + request.user.profile, request.auth, source=request.user.kwargs.get("source") + ) + ) class UserList(APIView): @@ -496,7 +508,7 @@ def post(self, request: Request): except Exception: raise AppApiException(500, _("Invalid encrypted data")) serializer_obj = ResetCurrentUserPassword(data=request_data) - if serializer_obj.reset_password(request.user.id): + if serializer_obj.reset_password(request.user.id, request.user.kwargs.get("source")): version, get_key = Cache_Version.TOKEN.value cache.delete(get_key(token=request.auth), version=version) return result.success(True) diff --git a/ui/src/conversation-panel/core/types.ts b/ui/src/conversation-panel/core/types.ts index 245b2064795..12829a41f57 100644 --- a/ui/src/conversation-panel/core/types.ts +++ b/ui/src/conversation-panel/core/types.ts @@ -10,6 +10,7 @@ export type ConversationAppInfo = ChatApplicationProfile export interface ConversationAccount { nickName?: string username?: string + source?: string token_quota?: ChatUserProfile['token_quota'] } diff --git a/ui/src/conversation-panel/left-sidebar/account-menu/index.vue b/ui/src/conversation-panel/left-sidebar/account-menu/index.vue index cba5d0c66a0..d64d7edb6de 100644 --- a/ui/src/conversation-panel/left-sidebar/account-menu/index.vue +++ b/ui/src/conversation-panel/left-sidebar/account-menu/index.vue @@ -3,7 +3,7 @@ import { computed, ref, useTemplateRef } from 'vue' import { useRoute, useRouter } from 'vue-router' import { useI18n } from 'vue-i18n' import type { Locale } from '@/locales/config' -import { QUOTA_TYPE } from '@/api/enums' +import { LOGIN_METHOD, QUOTA_TYPE } from '@/api/enums' import ChatUserApi from '@/api/chat/chat-user' import { useConversationListStore } from '../conversation-list/index' import ApiKeyDialog from './ApiKeyDialog.vue' @@ -118,7 +118,7 @@ const goLogin = () => { - + {{ t('auth.changePassword.title') }} diff --git a/ui/src/conversation-panel/view/chat/index.ts b/ui/src/conversation-panel/view/chat/index.ts index 782b9d42b63..4e63afc97c0 100644 --- a/ui/src/conversation-panel/view/chat/index.ts +++ b/ui/src/conversation-panel/view/chat/index.ts @@ -98,7 +98,9 @@ export function createChatConversation(routing: ChatConversationRouting = useApp rename: api.rename, account: computed(() => { const profile = user.chatUserProfile - return profile?.username ? { nickName: profile.nick_name, username: profile.username, token_quota: profile.token_quota } : null + return profile?.username + ? { nickName: profile.nick_name, username: profile.username, source: profile.source, token_quota: profile.token_quota } + : null }), appInfo, }) diff --git a/ui/src/conversation-panel/view/debug/index.ts b/ui/src/conversation-panel/view/debug/index.ts index c5feb74169c..d63e2e006a5 100644 --- a/ui/src/conversation-panel/view/debug/index.ts +++ b/ui/src/conversation-panel/view/debug/index.ts @@ -45,7 +45,11 @@ export function createDebugConversation(application: Readonly (user.userInfo ? { nickName: user.userInfo.nick_name, username: user.userInfo.username } : null)), + account: computed(() => + user.userInfo + ? { nickName: user.userInfo.nick_name, username: user.userInfo.username, source: user.userInfo.source } + : null, + ), appInfo, }) const msgs = createMessageListStore({ diff --git a/ui/src/layout/avatar-dropdown/index.vue b/ui/src/layout/avatar-dropdown/index.vue index 7c36f064fa5..3dd5bed8809 100644 --- a/ui/src/layout/avatar-dropdown/index.vue +++ b/ui/src/layout/avatar-dropdown/index.vue @@ -113,7 +113,10 @@ function toUrl(url?: string) { - + {{ t('auth.changePassword.title') }} diff --git a/ui/src/views/system/chat-management/users/index.vue b/ui/src/views/system/chat-management/users/index.vue index 664b47c078a..45b4bef6884 100644 --- a/ui/src/views/system/chat-management/users/index.vue +++ b/ui/src/views/system/chat-management/users/index.vue @@ -274,7 +274,11 @@ onMounted(() => loadChatUsers()) - + diff --git a/ui/src/views/system/identity/users/index.vue b/ui/src/views/system/identity/users/index.vue index e25946fbe1f..59ae5da0b39 100644 --- a/ui/src/views/system/identity/users/index.vue +++ b/ui/src/views/system/identity/users/index.vue @@ -285,7 +285,11 @@ onMounted(() => loadSystemUsers()) - +