diff --git a/app/api/endpoints/message.py b/app/api/endpoints/message.py index e79b0db66..b5f3eeb3d 100644 --- a/app/api/endpoints/message.py +++ b/app/api/endpoints/message.py @@ -26,8 +26,8 @@ from app.application.configuration import ( get_api_runtime_config_snapshot, get_configured_system_config, ) -from app.application.messaging.message import MessageQueryService -from app.application.notification import get_notification_configs +from app.application.messaging.message import MessageQueryService, MessageViewer +from app.application.notification import get_notification_configs, get_user_notification_types from app.chain.message import MessageChain from app.runtime.log import logger from app.runtime.tasks import TaskRegistry @@ -49,6 +49,21 @@ router = ResponseAPIRouter() _WNS_DEFAULT_TTL = 86400 +def _message_viewer(token_data: _SchemaTokenPayload) -> MessageViewer: + """ + 把访问令牌载荷转换为消息读取主体。 + + :param token_data: 已验证的访问令牌载荷 + :return: 用于确定可见范围的读取主体 + """ + super_user = bool(token_data.super_user) + return MessageViewer( + super_user=super_user, + userid=str(token_data.sub or ""), + visible_mtypes=None if super_user else get_user_notification_types(), + ) + + class WebPushError(Protocol): """ Web Push 订阅状态判断所需的最小异常协议。 @@ -229,17 +244,19 @@ async def web_message( response_model=List[_SchemaMessageHistoryItem], ) async def get_message_history( - _: _SchemaTokenPayload = Depends(verify_token), + token_data: _SchemaTokenPayload = Depends(verify_token), service: MessageQueryService = Depends(get_message_query_service), page: PositivePageParam = 1, count: PositiveCountParam = 20, ) -> List[_SchemaMessageHistoryItem]: """ - 分页获取消息表中的全部历史记录,包含接收消息与发送通知。 + 分页获取消息历史记录,包含接收消息与发送通知。 + + 超级用户返回全部记录;其他用户只返回发送范围为全部用户的通知,以及本人产生的记录。 旧路径 GET /api/v1/message/web 作为兼容入口保留相同行为;仅查询系统已发送通知时使用 GET /api/v1/message/notification。 - :param _: 已验证的访问令牌载荷 + :param token_data: 已验证的访问令牌载荷,用于确定可见范围 :param service: 消息历史查询服务 :param page: 页码,从 1 开始,最小为 1;直接调用传入 None 时默认第 1 页 :param count: 每页最多返回条数,最小为 1;直接调用传入 None 时默认 20 条 @@ -248,13 +265,14 @@ async def get_message_history( messages = await service.list_history( page=page if page is not None else 1, count=count if count is not None else 20, + viewer=_message_viewer(token_data), ) return [_SchemaMessageHistoryItem(**message) for message in messages] @router.get("/notification", summary="获取通知消息", response_model=List[_SchemaMessageHistoryItem]) async def get_notification_message( - _: _SchemaTokenPayload = Depends(verify_token), + token_data: _SchemaTokenPayload = Depends(verify_token), service: MessageQueryService = Depends(get_message_query_service), page: PositivePageParam = 1, count: PositiveCountParam = 20, @@ -262,7 +280,9 @@ async def get_notification_message( """ 获取清理水位之后系统发送的通知消息列表,仅包含发送方向(action=1)记录。 - :param _: 已验证的访问令牌载荷 + 超级用户返回全部通知;其他用户只返回发送范围为全部用户的通知,以及本人产生的记录。 + + :param token_data: 已验证的访问令牌载荷,用于确定可见范围 :param service: 消息历史查询服务 :param page: 页码,从 1 开始,最小为 1;直接调用传入 None 时默认第 1 页 :param count: 每页最多返回条数,最小为 1;直接调用传入 None 时默认 20 条 @@ -275,6 +295,7 @@ async def get_notification_message( all_clear_before=_format_notification_clear_time(clear_before.all), system_clear_before=_format_notification_clear_time(clear_before.system), media_clear_before=_format_notification_clear_time(clear_before.media), + viewer=_message_viewer(token_data), ) return [_SchemaMessageHistoryItem(**message) for message in messages] diff --git a/app/application/messaging/message.py b/app/application/messaging/message.py index c1c4dbec0..97d4f63df 100644 --- a/app/application/messaging/message.py +++ b/app/application/messaging/message.py @@ -13,9 +13,10 @@ import socket import threading import time from contextvars import Context, copy_context +from dataclasses import dataclass from datetime import datetime from functools import partial -from typing import Any, Callable, Dict, List, Literal, Optional, Protocol, Union, cast, overload +from typing import Any, Callable, Dict, List, Literal, Optional, Protocol, Sequence, Union, cast, overload from jinja2 import Template @@ -46,19 +47,55 @@ _MESSAGE_QUEUE_STOP_TIMEOUT_SECONDS = 10.0 _SSE_QUEUE_MAXSIZE = 100 +@dataclass(frozen=True) +class MessageViewer: + """ + 消息历史与通知的读取主体,用于确定可见范围。 + + :ivar super_user: 是否超级用户,超管不受可见范围限制 + :ivar userid: 调用者用户标识,用于匹配本人产生的记录 + :ivar visible_mtypes: 允许普通用户查看的通知场景值,由调用方按通知场景配置解析 + """ + + super_user: bool + userid: Optional[str] = None + visible_mtypes: Optional[Sequence[str]] = None + + +def _visibility_kwargs(viewer: Optional[MessageViewer]) -> dict[str, Any]: + """ + 把读取主体转换为持久化层可见性条件参数。 + + :param viewer: 读取主体,None 表示内部调用不限制可见范围 + :return: 持久化查询的可见性关键字参数 + """ + if viewer is None or viewer.super_user: + return {} + return { + "visible_mtypes": viewer.visible_mtypes or (), + "visible_userid": viewer.userid, + } + + class AsyncMessageQueryRepository(Protocol): """ 消息查询用例依赖的异步持久化端口。 """ async def async_list_by_page( - self, page: int = 1, count: int = 30 + self, + page: int = 1, + count: int = 30, + visible_mtypes: Optional[Sequence[str]] = None, + visible_userid: Optional[str] = None, ) -> list[Any]: """ 分页读取全部消息历史记录,不区分渠道与收发方向。 :param page: 页码,从 1 开始 :param count: 每页最多返回的消息数,默认 30 + :param visible_mtypes: 允许普通用户查看的通知场景值,None 表示不限制 + :param visible_userid: 允许查看本人记录的用户标识 :return: 按记录时间和主键降序排列的消息记录 """ ... @@ -70,6 +107,8 @@ class AsyncMessageQueryRepository(Protocol): all_clear_before: Optional[str] = None, system_clear_before: Optional[str] = None, media_clear_before: Optional[str] = None, + visible_mtypes: Optional[Sequence[str]] = None, + visible_userid: Optional[str] = None, ) -> list[Any]: """ 分页读取清理水位之后的通知消息。 @@ -79,6 +118,8 @@ class AsyncMessageQueryRepository(Protocol): :param all_clear_before: 全部通知的清理时间水位,按存储层时间字符串比较;None 表示不限制 :param system_clear_before: 无图片通知的清理时间水位,None 表示不限制此类消息 :param media_clear_before: 含图片通知的清理时间水位,None 表示不限制此类消息 + :param visible_mtypes: 允许普通用户查看的通知场景值,None 表示不限制 + :param visible_userid: 允许查看本人记录的用户标识 :return: 记录时间严格晚于相应水位的已发送通知,按时间和主键降序排列 """ ... @@ -97,15 +138,25 @@ class MessageQueryService: """ self._repository = repository - async def list_history(self, page: int = 1, count: int = 20) -> list[dict[str, Any]]: + async def list_history( + self, + page: int = 1, + count: int = 20, + viewer: Optional[MessageViewer] = None, + ) -> list[dict[str, Any]]: """ 分页返回可由 API 模型消费的全部消息历史字典,包含接收消息与发送通知。 :param page: 页码,从 1 开始 :param count: 每页最多返回的消息数,默认 20 + :param viewer: 读取主体,None 或超管时不限制可见范围 :return: 按记录时间和主键降序排列的消息字典列表 """ - messages = await self._repository.async_list_by_page(page=page, count=count) + messages = await self._repository.async_list_by_page( + page=page, + count=count, + **_visibility_kwargs(viewer), + ) result: list[dict[str, Any]] = [] for message in messages: try: @@ -121,6 +172,7 @@ class MessageQueryService: all_clear_before: Optional[str] = None, system_clear_before: Optional[str] = None, media_clear_before: Optional[str] = None, + viewer: Optional[MessageViewer] = None, ) -> list[dict[str, Any]]: """ 分页返回清理水位之后的系统已发送通知消息字典。 @@ -130,6 +182,7 @@ class MessageQueryService: :param all_clear_before: 全部通知的清理时间水位,None 表示不限制 :param system_clear_before: 无图片系统通知的清理时间水位,None 表示不限制 :param media_clear_before: 含图片媒体通知的清理时间水位,None 表示不限制 + :param viewer: 读取主体,None 或超管时不限制可见范围 :return: 仅包含已发送通知(action=1)且晚于相应清理水位的消息字典列表 """ messages = await self._repository.async_list_sent_by_page( @@ -138,6 +191,7 @@ class MessageQueryService: all_clear_before=all_clear_before, system_clear_before=system_clear_before, media_clear_before=media_clear_before, + **_visibility_kwargs(viewer), ) return [message.to_dict() for message in messages] diff --git a/app/application/notification.py b/app/application/notification.py index aeb819ff4..af2a141f5 100644 --- a/app/application/notification.py +++ b/app/application/notification.py @@ -64,3 +64,14 @@ def get_notification_switch(mtype: MessageType) -> str: if switch.type == mtype.value: return switch.action or "admin" return "admin" + + +def get_user_notification_types() -> tuple[str, ...]: + """ + 返回发送范围为全部用户的通知场景值,供读取侧过滤普通用户可见记录。 + """ + return tuple( + mtype.value + for mtype in MessageType + if get_notification_switch(mtype) == "all" + ) diff --git a/app/db/models/message.py b/app/db/models/message.py index 647ed246a..3ffe5e837 100644 --- a/app/db/models/message.py +++ b/app/db/models/message.py @@ -4,7 +4,7 @@ 会话及事务由调用方管理,本模块不负责提交或回滚。 """ -from typing import Any, List, Optional +from typing import Any, List, Optional, Sequence from sqlalchemy import JSON, Index, Integer, String, and_, delete, or_, select from sqlalchemy.ext.asyncio import AsyncSession @@ -89,15 +89,50 @@ class Message(Base): select(cls.id).where(cls.source == source).limit(1) ).scalars().first() is not None + @classmethod + def _visible_clause( + cls, + visible_mtypes: Optional[Sequence[str]] = None, + visible_userid: Optional[str] = None, + ) -> Optional[Any]: + """ + 构造读取侧可见性条件:广播场景的通知或本人产生的记录。 + + :param visible_mtypes: 允许普通用户查看的通知场景值,None 表示不限制 + :param visible_userid: 允许查看本人记录的用户标识 + :return: 查询条件,None 表示不限制可见范围 + """ + if visible_mtypes is None: + return None + conditions = [cls.mtype.in_(visible_mtypes)] + if visible_userid: + conditions.append(cls.userid == visible_userid) + return or_(*conditions) + @classmethod async def async_list_by_page( - cls, db: AsyncSession, page: int = 1, count: int = 30 + cls, + db: AsyncSession, + page: int = 1, + count: int = 30, + visible_mtypes: Optional[Sequence[str]] = None, + visible_userid: Optional[str] = None, ) -> List["Message"]: """ 异步分页获取消息记录。 + + :param db: 数据库会话 + :param page: 页码,从 1 开始 + :param count: 每页最多返回的消息数 + :param visible_mtypes: 允许普通用户查看的通知场景值,None 表示不限制 + :param visible_userid: 允许查看本人记录的用户标识 """ + statement = select(cls) + visible = cls._visible_clause(visible_mtypes, visible_userid) + if visible is not None: + statement = statement.where(visible) result = await db.execute( - select(cls) + statement .order_by(cls.reg_time.desc(), cls.id.desc()) .offset((page - 1) * count) .limit(count) @@ -113,9 +148,20 @@ class Message(Base): all_clear_before: Optional[str] = None, system_clear_before: Optional[str] = None, media_clear_before: Optional[str] = None, + visible_mtypes: Optional[Sequence[str]] = None, + visible_userid: Optional[str] = None, ) -> List["Message"]: """ 分页获取系统发送的通知消息。 + + :param db: 数据库会话 + :param page: 页码,从 1 开始 + :param count: 每页最多返回的消息数 + :param all_clear_before: 全部通知的清理水位 + :param system_clear_before: 无图片系统通知的清理水位 + :param media_clear_before: 含图片媒体通知的清理水位 + :param visible_mtypes: 允许普通用户查看的通知场景值,None 表示不限制 + :param visible_userid: 允许查看本人记录的用户标识 """ statement = select(cls).where(cls.action == 1) if all_clear_before: @@ -135,6 +181,9 @@ class Message(Base): cls.reg_time > media_clear_before, ) ) + visible = cls._visible_clause(visible_mtypes, visible_userid) + if visible is not None: + statement = statement.where(visible) result = await db.execute( statement .order_by(cls.reg_time.desc(), cls.id.desc()) diff --git a/app/db/oper/message.py b/app/db/oper/message.py index f55ccb873..a19054514 100644 --- a/app/db/oper/message.py +++ b/app/db/oper/message.py @@ -3,9 +3,9 @@ """ import time -from typing import Any, Optional, Union +from typing import Any, Optional, Sequence, Union -from sqlalchemy import and_, or_, select +from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import Session @@ -136,26 +136,32 @@ class MessageOper(DbOper): return exists async def async_list_by_page( - self, page: int = 1, count: int = 30 + self, + page: int = 1, + count: int = 30, + visible_mtypes: Optional[Sequence[str]] = None, + visible_userid: Optional[str] = None, ) -> list[Message]: """ 异步分页获取全部消息记录,不区分渠道与收发方向。 :param page: 页码,从 1 开始 :param count: 每页最多返回的消息数,默认 30 + :param visible_mtypes: 允许普通用户查看的通知场景值,None 表示不限制 + :param visible_userid: 允许查看本人记录的用户标识 :return: 按登记时间和主键倒序排列的消息记录列表 """ async def query(session: AsyncSession) -> list[Message]: """ 在调用方异步会话中执行消息分页查询。 """ - result = await session.execute( - select(Message) - .order_by(Message.reg_time.desc(), Message.id.desc()) - .offset((page - 1) * count) - .limit(count) + return await Message.async_list_by_page( + session, + page=page, + count=count, + visible_mtypes=visible_mtypes, + visible_userid=visible_userid, ) - return list(result.scalars().all()) messages: list[Message] = await self._execute_async_query(query) return messages @@ -167,35 +173,34 @@ class MessageOper(DbOper): all_clear_before: Optional[str] = None, system_clear_before: Optional[str] = None, media_clear_before: Optional[str] = None, + visible_mtypes: Optional[Sequence[str]] = None, + visible_userid: Optional[str] = None, ) -> list[Message]: """ 分页获取系统发送的通知消息。 + + :param page: 页码,从 1 开始 + :param count: 每页最多返回的消息数,默认 30 + :param all_clear_before: 全部通知的清理水位 + :param system_clear_before: 无图片系统通知的清理水位 + :param media_clear_before: 含图片媒体通知的清理水位 + :param visible_mtypes: 允许普通用户查看的通知场景值,None 表示不限制 + :param visible_userid: 允许查看本人记录的用户标识 """ async def query(session: AsyncSession) -> list[Message]: """ 在调用方异步会话中执行通知消息分页查询。 """ - statement = select(Message).where(Message.action == 1) - if all_clear_before: - statement = statement.where(Message.reg_time > all_clear_before) - if system_clear_before: - statement = statement.where(or_( - and_(Message.image.isnot(None), Message.image != ""), - Message.reg_time > system_clear_before, - )) - if media_clear_before: - statement = statement.where(or_( - Message.image.is_(None), - Message.image == "", - Message.reg_time > media_clear_before, - )) - result = await session.execute( - statement - .order_by(Message.reg_time.desc(), Message.id.desc()) - .offset((page - 1) * count) - .limit(count) + return await Message.async_list_sent_by_page( + session, + page=page, + count=count, + all_clear_before=all_clear_before, + system_clear_before=system_clear_before, + media_clear_before=media_clear_before, + visible_mtypes=visible_mtypes, + visible_userid=visible_userid, ) - return list(result.scalars().all()) messages: list[Message] = await self._execute_async_query(query) return messages diff --git a/tests/api/endpoints/test_api_optional_inputs.py b/tests/api/endpoints/test_api_optional_inputs.py index 16070f5da..8be23f599 100644 --- a/tests/api/endpoints/test_api_optional_inputs.py +++ b/tests/api/endpoints/test_api_optional_inputs.py @@ -11,11 +11,13 @@ from fastapi import HTTPException from pydantic import TypeAdapter from app.api.endpoints import bangumi, download, history, mediaserver, message, search, site, tmdb, transfer +from app.application.messaging.message import MessageViewer from app.domain.context import MediaInfo from app.schemas.context import MediaInfo as MediaInfoInput from app.schemas.context import SubtitleInfo from app.schemas.file import FileItem from app.schemas.site import SiteCategory +from app.schemas.token import TokenPayload from app.schemas.transfer import ManualTransferItem from app.schemas.types import MediaType @@ -58,8 +60,14 @@ def test_history_and_web_message_optional_pagination(): query.list_transfer.assert_awaited_once_with(title=None, page=1, count=30, status=None) assert response.success is True messages = SimpleNamespace(list_history=AsyncMock(return_value=[])) - assert asyncio.run(message.get_message_history(service=messages, page=None, count=None, _=None)) == [] - messages.list_history.assert_awaited_once_with(page=1, count=20) + token = TokenPayload(sub=1, username="admin", super_user=True) + assert asyncio.run(message.get_message_history( + service=messages, page=None, count=None, token_data=token)) == [] + messages.list_history.assert_awaited_once_with( + page=1, + count=20, + viewer=MessageViewer(super_user=True, userid="1"), + ) @pytest.mark.parametrize("season", [None, 2]) diff --git a/tests/api/pagination/test_api_pagination_validation.py b/tests/api/pagination/test_api_pagination_validation.py index c224eb4e2..ed1ffd094 100644 --- a/tests/api/pagination/test_api_pagination_validation.py +++ b/tests/api/pagination/test_api_pagination_validation.py @@ -21,6 +21,7 @@ from app.api.dependencies.history import get_history_query_service from app.api.dependencies.subscription import get_subscription_query_service from app.api.endpoints import agent, history, message, subscribe from app.api.response import ResponseAPIRoute +from app.application.messaging.message import MessageViewer from app.factory import ( localized_http_exception_handler, localized_unhandled_exception_handler, @@ -190,8 +191,13 @@ def test_database_paginated_endpoints_preserve_defaults_and_large_transfer_page_ all_clear_before=None, system_clear_before=None, media_clear_before=None, + viewer=MessageViewer(super_user=True, userid="1"), + ) + stubs["message"].list_history.assert_awaited_once_with( + page=1, + count=20, + viewer=MessageViewer(super_user=True, userid="1"), ) - stubs["message"].list_history.assert_awaited_once_with(page=1, count=20) stubs["agent_chat"].list.assert_awaited_once() assert stubs["agent_chat"].list.await_args.kwargs == {"page": 1, "count": 30} stubs["history"].list_download.assert_awaited_once_with(page=1, count=30) @@ -239,7 +245,12 @@ def test_direct_calls_with_none_pagination_fall_back_to_endpoint_defaults( ) assert asyncio.run( - message.get_notification_message(_=None, service=message_service, page=None, count=None) + message.get_notification_message( + token_data=TokenPayload(sub=1, username="admin", super_user=True), + service=message_service, + page=None, + count=None, + ) ) == [] assert asyncio.run( history.download_history( @@ -267,6 +278,7 @@ def test_direct_calls_with_none_pagination_fall_back_to_endpoint_defaults( all_clear_before=None, system_clear_before=None, media_clear_before=None, + viewer=MessageViewer(super_user=True, userid="1"), ) history_service.list_download.assert_awaited_once_with(page=1, count=30) subscription_service.list_history.assert_awaited_once_with( diff --git a/tests/integration/messaging/test_message_notifications.py b/tests/integration/messaging/test_message_notifications.py index 322ece79d..0477464e2 100644 --- a/tests/integration/messaging/test_message_notifications.py +++ b/tests/integration/messaging/test_message_notifications.py @@ -16,7 +16,12 @@ from app.api.endpoints.message import ( get_notification_message, ) from app.api.endpoints.system import get_message -from app.application.messaging.message import _SSE_QUEUE_MAXSIZE, MessageHelper, MessageQueryService +from app.application.messaging.message import ( + _SSE_QUEUE_MAXSIZE, + MessageHelper, + MessageQueryService, + MessageViewer, +) from app.chain.base import ChainBase from app.db.models.message import Message as MessageModel from app.db.oper.message import MessageOper @@ -25,6 +30,7 @@ from app.db.session import AsyncSessionFactory, SessionFactory from app.domain.context import Context, MediaInfo, TorrentInfo from app.domain.meta.metabase import MetaBase from app.schemas.message import Message, MessageClearScope +from app.schemas.token import TokenPayload from app.schemas.types import MediaType, MessageType, SystemConfigKey @@ -50,6 +56,13 @@ def _isolate_message_state() -> Iterator[None]: _clear_messages() +def _admin_token() -> TokenPayload: + """ + 构造超管令牌载荷,直调端点时用于关闭可见性过滤。 + """ + return TokenPayload(sub=1, username="admin", super_user=True) + + def _reset_message_helper(helper: MessageHelper) -> None: """ 清空单例消息队列和去重缓存,避免用例间互相影响。 @@ -84,6 +97,7 @@ def test_notification_history_only_lists_sent_messages() -> None: """ async with AsyncSessionFactory() as db: items = await get_notification_message( + token_data=_admin_token(), service=MessageQueryService(MessageOper(db)), page=1, count=10, @@ -105,8 +119,6 @@ def test_message_history_endpoint_returns_all_directions_and_keeps_web_compat() from app.adapters.web.security.access import verify_token from app.api.dependencies.agent import get_message_query_service - from app.schemas.token import TokenPayload - _clear_messages() oper = MessageOper() oper.add(title="智能体回复", text="已处理", action=1, mtype=MessageType.Agent) @@ -119,6 +131,7 @@ def test_message_history_endpoint_returns_all_directions_and_keeps_web_compat() """ async with AsyncSessionFactory() as db: items = await get_message_history( + token_data=_admin_token(), service=MessageQueryService(MessageOper(db)), page=1, count=10, @@ -313,7 +326,8 @@ def test_notification_clear_marker_filters_history_across_requests() -> None: """ async with AsyncSessionFactory() as db: messages = await get_notification_message( - service=MessageQueryService(MessageOper(db)) + token_data=_admin_token(), + service=MessageQueryService(MessageOper(db)), ) return [message.title for message in messages] @@ -591,3 +605,124 @@ def test_transient_media_and_torrent_lists_skip_history_but_dispatch(monkeypatch assert MessageOper().list_by_page(page=1, count=10) == [] assert send_message.call_count == 2 + + +def test_user_notification_types_keep_only_broadcast_scope(monkeypatch) -> None: + """ + 只有发送范围为全部用户的场景进入普通用户可见类型。 + """ + from app.application import notification as notification_application + + monkeypatch.setattr( + notification_application, + "get_notification_switch", + lambda mtype: "all" if mtype == MessageType.Organize else "admin", + ) + + assert notification_application.get_user_notification_types() == ( + MessageType.Organize.value, + ) + + +def test_message_query_service_hides_records_outside_visible_scope() -> None: + """ + 普通用户读取历史时只返回广播通知与本人记录,超管不受限制。 + """ + _clear_messages() + oper = MessageOper() + oper.add(title="入库广播", text="已入库", action=1, mtype=MessageType.Organize) + oper.add(title="站点告警", text="站点失效", action=1, mtype=MessageType.SiteMessage) + oper.add(title="本人提问", text="/ai 帮我搜索", action=0, userid="7") + oper.add(title="他人提问", text="/ai 帮我搜索", action=0, userid="9") + visible_mtypes = (MessageType.Organize.value,) + + async def _titles(viewer: MessageViewer | None) -> list[str]: + """ + 按指定读取主体查询消息历史标题。 + """ + async with AsyncSessionFactory() as db: + items = await MessageQueryService(MessageOper(db)).list_history( + page=1, + count=10, + viewer=viewer, + ) + return [item["title"] for item in items] + + assert asyncio.run(_titles(None)) == ["他人提问", "本人提问", "站点告警", "入库广播"] + assert asyncio.run(_titles(MessageViewer(super_user=True))) == [ + "他人提问", + "本人提问", + "站点告警", + "入库广播", + ] + assert asyncio.run(_titles(MessageViewer( + super_user=False, userid="7", visible_mtypes=visible_mtypes))) == [ + "本人提问", + "入库广播", + ] + assert asyncio.run(_titles(MessageViewer( + super_user=False, visible_mtypes=visible_mtypes))) == ["入库广播"] + assert asyncio.run(_titles(MessageViewer(super_user=False))) == [] + + +def test_message_endpoints_filter_admin_scope_for_normal_user(monkeypatch) -> None: + """ + 普通用户的消息历史与通知接口只返回广播通知与本人记录。 + """ + from fastapi import FastAPI + from fastapi.testclient import TestClient + + from app.adapters.web.security.access import verify_token + from app.api.dependencies.agent import get_message_query_service + + _clear_messages() + oper = MessageOper() + oper.add(title="入库广播", text="已入库", action=1, mtype=MessageType.Organize) + oper.add(title="站点告警", text="站点失效", action=1, mtype=MessageType.SiteMessage) + oper.add(title="无类型通知", text="未分类", action=1) + oper.add(title="本人提问", text="/ai 帮我搜索", action=0, userid="7") + oper.add(title="他人提问", text="/ai 帮我搜索", action=0, userid="9") + monkeypatch.setattr( + "app.api.endpoints.message.get_user_notification_types", + lambda: (MessageType.Organize.value,), + ) + + class _SessionRepository: + """ + 在测试数据库会话中执行可见性查询的消息仓储。 + """ + + async def async_list_by_page(self, **kwargs) -> list[MessageModel]: + """ + 按可见性参数查询全部方向的消息记录。 + """ + async with AsyncSessionFactory() as db: + return await MessageModel.async_list_by_page(db, **kwargs) + + async def async_list_sent_by_page(self, **kwargs) -> list[MessageModel]: + """ + 按可见性参数查询发送方向的消息记录。 + """ + async with AsyncSessionFactory() as db: + return await MessageModel.async_list_sent_by_page(db, **kwargs) + + def _override_service() -> MessageQueryService: + """ + 提供绑定测试数据库会话的消息历史查询服务。 + """ + return MessageQueryService(_SessionRepository()) + + app = FastAPI() + app.include_router(message_endpoint.router, prefix="/api/v1/message") + app.dependency_overrides[verify_token] = lambda: TokenPayload( + sub=7, + username="user", + super_user=False, + ) + app.dependency_overrides[get_message_query_service] = _override_service + with TestClient(app) as client: + history = client.get("/api/v1/message/history?page=1&count=10").json()["data"] + notifications = client.get("/api/v1/message/notification?page=1&count=10").json()["data"] + + assert [row["title"] for row in history] == ["本人提问", "入库广播"] + assert [row["title"] for row in notifications] == ["入库广播"] diff --git a/tests/integration/messaging/test_message_posters.py b/tests/integration/messaging/test_message_posters.py index 72702c51d..cd621df71 100644 --- a/tests/integration/messaging/test_message_posters.py +++ b/tests/integration/messaging/test_message_posters.py @@ -18,6 +18,7 @@ from app.db.oper.message import MessageOper from app.db.session import AsyncSessionFactory from app.domain.context import MediaInfo, MusicInfo from app.schemas.message import Message +from app.schemas.token import TokenPayload @pytest.mark.parametrize("has_poster", [True, False]) @@ -77,7 +78,10 @@ def test_notification_history_preserves_poster_and_legacy_null(async_write: bool else: MessageOper().add(**payload) MessageOper().add(title=f"{title}-legacy", image=payload["image"]) - messages = await get_notification_message(service=MessageQueryService(MessageOper(db))) + messages = await get_notification_message( + token_data=TokenPayload(sub=1, username="admin", super_user=True), + service=MessageQueryService(MessageOper(db)), + ) current = next(item for item in messages if item.title == title) legacy = next(item for item in messages if item.title == f"{title}-legacy") assert current.image == payload["image"]