diff --git a/apps/chat/serializers/portal.py b/apps/chat/serializers/portal.py index 2f8aa6facef..2d6a3dfabdc 100644 --- a/apps/chat/serializers/portal.py +++ b/apps/chat/serializers/portal.py @@ -14,6 +14,7 @@ from application.models import Application, Chat from application.models.application_access_token import ApplicationAccessToken +from common.auth.handle.impl.chat_user_token import login_type_list from common.constants.cache_version import Cache_Version from common.database_model_manage.database_model_manage import DatabaseModelManage from common.db.search import page_search @@ -73,19 +74,33 @@ class PortalApplicationAuthMixin: """门户应用授权过滤公共逻辑""" @staticmethod - def get_authorized_application_ids(user_id): + def get_authorized_application_ids(user_id, login_type=None, check_login_type=True): + """ + check_login_type=True(登录会话):登录认证应用需要包含当前登录方式; + check_login_type=False(对话用户 API Key):不校验登录方式,返回授权给该用户的全部应用。 + """ public_apps = ApplicationAccessToken.objects.filter( application_id=OuterRef("id"), authentication=False, is_active=True ) - if not ChatUser.objects.filter(id=user_id).exists(): + # 非登录用户、或登录方式无效时,仅返回匿名(公开)应用 + invalid_login_type = check_login_type and (not login_type or login_type.upper() not in login_type_list) + if invalid_login_type or not ChatUser.objects.filter(id=user_id).exists(): return ( Application.objects.filter(is_publish=True, is_portal=True) .filter(Exists(public_apps)) .values_list("id", flat=True) ) + # 登录认证应用:登录会话需要应用的登录方式包含当前登录方式(与 chat_user_token.get_auth 保持一致) authed_token_exists = ApplicationAccessToken.objects.filter( - application_id=OuterRef("id"), authentication=True, is_active=True + application_id=OuterRef("id"), + authentication=True, + is_active=True, + authentication_value__type="login", ) + if check_login_type: + authed_token_exists = authed_token_exists.filter( + authentication_value__login_value__contains=[login_type.upper()] + ) direct_auth = ResourceChatUserAuthorize.objects.filter( resource_id=OuterRef("id"), resource_type=ResourceType.APPLICATION.value, is_auth=True, user_id=user_id ) @@ -128,11 +143,13 @@ def get_query_set(self): queryset = queryset.filter(name__icontains=name) return queryset.order_by("-create_time") - def page(self, current_page, page_size, user_id, with_valid=True): + def page(self, current_page, page_size, user_id, login_type, check_login_type=True, with_valid=True): if with_valid: self.is_valid(raise_exception=True) queryset = self.get_query_set() - queryset = queryset.filter(id__in=self.get_authorized_application_ids(user_id)) + queryset = queryset.filter( + id__in=self.get_authorized_application_ids(user_id, login_type, check_login_type) + ) return page_search( current_page, page_size, @@ -172,25 +189,25 @@ class Query(PortalApplicationAuthMixin, serializers.Serializer): required=False, allow_blank=True, label=_("Application Name"), help_text=_("Application name") ) - def get_query_set(self, user_id): + def get_query_set(self, user_id, login_type, check_login_type=True): # 主表是应用:返回用户有权限访问的已发布门户应用 queryset = Application.objects.filter( is_publish=True, is_portal=True, - id__in=self.get_authorized_application_ids(user_id), + id__in=self.get_authorized_application_ids(user_id, login_type, check_login_type), ) name = self.data.get("name") if name: queryset = queryset.filter(name__icontains=name) return queryset.order_by("-create_time") - def page(self, current_page, page_size, user_id, with_valid=True): + def page(self, current_page, page_size, user_id, login_type, check_login_type=True, with_valid=True): if with_valid: self.is_valid(raise_exception=True) result = page_search( current_page, page_size, - self.get_query_set(user_id), + self.get_query_set(user_id, login_type, check_login_type), post_records_handler=lambda app: { "id": str(app.id), "name": app.name, @@ -215,16 +232,18 @@ class PortalConversationQuerySerializer(PortalApplicationAuthMixin, serializers. required=False, allow_blank=True, label=_("Abstract"), help_text=_("Conversation abstract keyword") ) - def _authorize(self, user_id): + def _authorize(self, user_id, login_type, check_login_type=True): application_id = str(self.data.get("application_id")) - authorized_ids = {str(item) for item in self.get_authorized_application_ids(user_id)} + authorized_ids = { + str(item) for item in self.get_authorized_application_ids(user_id, login_type, check_login_type) + } if application_id not in authorized_ids: raise serializers.ValidationError(_("Application is not authorized")) - def page(self, current_page, page_size, user_id, with_valid=True): + def page(self, current_page, page_size, user_id, login_type, check_login_type=True, with_valid=True): if with_valid: self.is_valid(raise_exception=True) - self._authorize(user_id) + self._authorize(user_id, login_type, check_login_type) application_id = self.data.get("application_id") queryset = Chat.objects.filter(application_id=application_id, chat_user_id=user_id, is_deleted=False).order_by( "-update_time", "id" diff --git a/apps/chat/tests/test_portal.py b/apps/chat/tests/test_portal.py index 66b4145689d..90ecaba37b5 100644 --- a/apps/chat/tests/test_portal.py +++ b/apps/chat/tests/test_portal.py @@ -39,7 +39,7 @@ def setUp(self): def test_grouped_history_returns_latest_five_when_history_setting_is_disabled(self): with patch("django.core.cache.cache.get", return_value=True): - result = PortalHistoricalConversationSerializer.Query(data={}).page(1, 20, self.user_id) + result = PortalHistoricalConversationSerializer.Query(data={}).page(1, 20, self.user_id, None) application = result["records"][0] self.assertFalse(application["show_history"]) @@ -52,7 +52,7 @@ def test_grouped_history_returns_latest_five_when_history_setting_is_disabled(se def test_application_history_remains_queryable_when_history_setting_is_disabled(self): with patch("django.core.cache.cache.get", return_value=True): result = PortalConversationQuerySerializer(data={"application_id": self.application.id}).page( - 1, 5, self.user_id + 1, 5, self.user_id, None ) self.assertEqual( diff --git a/apps/chat/tests/test_portal_login_type.py b/apps/chat/tests/test_portal_login_type.py new file mode 100644 index 00000000000..81adb3ad9a4 --- /dev/null +++ b/apps/chat/tests/test_portal_login_type.py @@ -0,0 +1,82 @@ +from django.test import TestCase + +from application.models import Application, ApplicationAccessToken, ApplicationFolder +from chat.serializers.portal import PortalApplicationAuthMixin +from common.auth.constants.group_constants import Group +from common.auth.handle.impl.chat_user_token import get_auth +from system_manage.models import ChatUser, ResourceChatUserAuthorize, ResourceType, UserGroup + + +class PortalLoginTypeFilterTests(TestCase): + def setUp(self): + folder, _ = ApplicationFolder.objects.get_or_create(id="default", defaults={"name": "默认分组"}) + self.public_application = Application.objects.create( + name="公开应用", folder=folder, is_publish=True, is_portal=True + ) + ApplicationAccessToken.objects.create( + application=self.public_application, access_token="portal-public-token", authentication=False + ) + self.local_application = Application.objects.create( + name="账号登录应用", folder=folder, is_publish=True, is_portal=True + ) + ApplicationAccessToken.objects.create( + application=self.local_application, + access_token="portal-local-token", + authentication=True, + authentication_value={"type": "login", "login_value": ["LOCAL"]}, + ) + self.user = ChatUser.objects.create( + username="portal-user", nick_name="Portal User", password="encrypted-password", source="LOCAL" + ) + group = UserGroup.objects.create(name="portal users") + ResourceChatUserAuthorize.objects.create( + user_group=group, + user=self.user, + resource_id=self.local_application.id, + resource_type=ResourceType.APPLICATION.value, + is_auth=True, + ) + + def authorized_ids(self, login_type, check_login_type=True): + return { + str(item) + for item in PortalApplicationAuthMixin.get_authorized_application_ids( + str(self.user.id), login_type, check_login_type + ) + } + + def test_matching_login_type_returns_login_application(self): + self.assertEqual( + self.authorized_ids("LOCAL"), {str(self.public_application.id), str(self.local_application.id)} + ) + + def test_unmatched_login_type_hides_login_application(self): + self.assertEqual(self.authorized_ids("OIDC"), {str(self.public_application.id)}) + + def test_missing_login_type_returns_only_public_applications(self): + self.assertEqual(self.authorized_ids(None), {str(self.public_application.id)}) + + def test_api_key_returns_all_authorized_applications_regardless_of_login_type(self): + self.assertEqual( + self.authorized_ids("OIDC", check_login_type=False), + {str(self.public_application.id), str(self.local_application.id)}, + ) + + def test_api_key_auth_grants_authorized_application_regardless_of_login_type(self): + permission_key = f"{Group.CHAT_USER}:r:{self.local_application.id}" + self.assertFalse(get_auth("OIDC", str(self.user.id), None).permissions.get(permission_key)) + self.assertTrue( + get_auth("OIDC", str(self.user.id), None, check_login_type=False).permissions.get(permission_key) + ) + + def test_application_api_key_is_treated_as_anonymous(self): + # ApplicationKey 的 Principal id 是应用 API Key 的 id,不带 login_type,只能看到公开应用 + application_api_key_id = "01a1f6cf-9369-77d2-abf6-70f9db09c495" + for check_login_type in (True, False): + ids = { + str(item) + for item in PortalApplicationAuthMixin.get_authorized_application_ids( + application_api_key_id, None, check_login_type + ) + } + self.assertEqual(ids, {str(self.public_application.id)}) diff --git a/apps/chat/views/v3/portal.py b/apps/chat/views/v3/portal.py index 1b5e7a1928e..27c67e5ffef 100644 --- a/apps/chat/views/v3/portal.py +++ b/apps/chat/views/v3/portal.py @@ -25,6 +25,11 @@ ) +def get_login_type_args(request: Request): + """门户授权过滤参数:(登录方式, 是否校验登录方式);对话用户 API Key 不校验登录方式""" + return request.user.kwargs.get("login_type"), request.user.kwargs.get("check_login_type", True) + + class PortalAuthProfile(APIView): @extend_schema( methods=["GET"], @@ -54,7 +59,7 @@ class PortalApplicationView(APIView): def get(self, request: Request, current_page: int, page_size: int): return result.success( PortalApplicationSerializer.Query(data={**query_params_to_single_dict(request.query_params)}).page( - current_page, page_size, str(request.user.id) + current_page, page_size, str(request.user.id), *get_login_type_args(request) ) ) @@ -75,7 +80,7 @@ def get(self, request: Request, current_page: int, page_size: int): return result.success( PortalHistoricalConversationSerializer.Query( data={**query_params_to_single_dict(request.query_params)} - ).page(current_page, page_size, str(request.user.id)) + ).page(current_page, page_size, str(request.user.id), *get_login_type_args(request)) ) @@ -98,5 +103,5 @@ def get(self, request: Request, application_id: str, current_page: int, page_siz **query_params_to_single_dict(request.query_params), "application_id": application_id, } - ).page(current_page, page_size, str(request.user.id)) + ).page(current_page, page_size, str(request.user.id), *get_login_type_args(request)) ) diff --git a/apps/common/auth/handle/impl/chat_user_key.py b/apps/common/auth/handle/impl/chat_user_key.py index 0eb67c0c7ab..6c6c4a99808 100644 --- a/apps/common/auth/handle/impl/chat_user_key.py +++ b/apps/common/auth/handle/impl/chat_user_key.py @@ -32,8 +32,9 @@ def handle(self, request, token: str, get_token_details): # 门户「智能体后端 API 访问」开关控制对话用户 API Key 的全部对话接口(含应用 MCP),知识库检索由独立开关控制 if not get_portal_setting("enable_api"): raise AppAuthenticationFailed(500, _("API service is disabled")) - auth = get_auth(chat_user.source, chat_user.id, None) - return Principal(str(chat_user.id), ChatUserType.CHAT_USER, profile=chat_user), auth + # API Key 不区分登录方式:可以访问授权给该用户(含所属用户组)的全部应用 + auth = get_auth(chat_user.source, chat_user.id, None, check_login_type=False) + return Principal(str(chat_user.id), ChatUserType.CHAT_USER, profile=chat_user, check_login_type=False), auth def support(self, request, token: str, get_token_details): return str(token).startswith("chat-") diff --git a/apps/common/auth/handle/impl/chat_user_token.py b/apps/common/auth/handle/impl/chat_user_token.py index 4b06f73ccea..f931da83e53 100644 --- a/apps/common/auth/handle/impl/chat_user_token.py +++ b/apps/common/auth/handle/impl/chat_user_token.py @@ -40,12 +40,17 @@ ] -def get_auth(login_type, user_id, application_id): +def get_auth(login_type, user_id, application_id, check_login_type=True): + """ + 计算对话用户的应用权限。 + check_login_type=True(登录会话):登录认证应用需要应用的登录方式包含当前登录方式,且用户/用户组被授权; + check_login_type=False(对话用户 API Key):不校验登录方式,只要用户/用户组被授权即可访问。 + """ application_access_token_list = QuerySet(ApplicationAccessToken).filter(is_active=True) # 匿名应用所有人都可以访问;登录用户额外可以访问已授权的登录认证应用(匿名 OR 登录授权) access_condition = Q(authentication=False) - if login_type_list.__contains__(login_type.upper()): + if not check_login_type or login_type_list.__contains__(login_type.upper()): user_group_ids = ( QuerySet(UserGroupRelation) .filter( @@ -73,12 +78,14 @@ def get_auth(login_type, user_id, application_id): ) .values_list("resource_id", flat=True) ) - access_condition |= ( + login_condition = ( Q(authentication=True) & Q(authentication_value__type="login") - & Q(authentication_value__login_value__contains=login_type) & (Q(application_id__in=group_qs) | Q(application_id__in=user_qs)) ) + if check_login_type: + login_condition &= Q(authentication_value__login_value__contains=login_type) + access_condition |= login_condition application_access_token_list = application_access_token_list.filter(access_condition) if application_id: application_access_token_list = application_access_token_list.filter(application_id=application_id) @@ -129,5 +136,7 @@ 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, source=source), auth - return Principal(user_id, _type, profile=chat_user, source=source), auth + return Principal( + user_id, _type, application_id=application_id, profile=chat_user, source=source, login_type=login_type + ), auth + return Principal(user_id, _type, profile=chat_user, source=source, login_type=login_type), auth diff --git a/apps/oss/serializers/file.py b/apps/oss/serializers/file.py index 7ea448c3c95..cb503b76338 100644 --- a/apps/oss/serializers/file.py +++ b/apps/oss/serializers/file.py @@ -270,7 +270,8 @@ def parse_file_token(mk_file_auth): chat_user = chat_user_api_key.user if chat_user_api_key else None if chat_user is None or not chat_user.is_active: _deny() - return ChatToken(str(chat_user.id), AuthenticationType.CHAT_USER, chat_user.source) + # API Key 不区分登录方式,按用户/用户组授权鉴权(与 ChatUserKey 保持一致) + return ChatToken(str(chat_user.id), AuthenticationType.CHAT_USER, chat_user.source, check_login_type=False) else: try: return parse_token(token=mk_file_auth) @@ -350,7 +351,12 @@ def _auth_chat(file, token): if not token.application_id == file.source_id: _deny() else: - user_auth = get_chat_auth(token.login_type, token.id, application_id) + user_auth = get_chat_auth( + token.login_type, + token.id, + application_id, + check_login_type=token.kwargs.get("check_login_type", True), + ) if not any( [ hasPermission(