diff --git a/app/adapters/web/security/access.py b/app/adapters/web/security/access.py index a09d5df58..e8e75a92d 100644 --- a/app/adapters/web/security/access.py +++ b/app/adapters/web/security/access.py @@ -331,6 +331,10 @@ def verify_token( if jwt_token: payload = _decode_or_http_error(jwt_token, "authentication") _validate_token_identity(payload) + if payload.agent_authorization_id: + if request.method != payload.agent_method or request.url.path != payload.agent_path: + raise HTTPException(status_code=403, detail="渠道凭据只能用于指定的业务操作") + return payload set_or_refresh_resource_token_cookie(request, response, payload) return payload if api_key: diff --git a/app/agent/api/executor.py b/app/agent/api/executor.py index 421d18823..a3305bf65 100644 --- a/app/agent/api/executor.py +++ b/app/agent/api/executor.py @@ -18,6 +18,7 @@ from app.agent.policy.api import ( ) from app.agent.policy.contracts import ActionEffect from app.agent.policy.sanitizer import stable_type_name +from app.agent.tools.base import run_agent_blocking from app.application.security.token import create_access_token from app.runtime.log import logger from app.runtime.priority import PRIORITY_HEADER, interactive_key @@ -55,6 +56,7 @@ class ApiExecutionContext: :param channel_user_id: 发起会话的用户在消息渠道内的原始标识,如 Telegram 用户 ID; 与渠道一起写入宿主令牌的签名声明,供命令回执等需要回复原渠道的场景使用, 不参与 API 用户鉴权;无渠道时为 None + :param authorization_id: 统一渠道成员身份;非渠道调用为空 """ user_id: str @@ -65,6 +67,7 @@ class ApiExecutionContext: source: str | None = None public_read_only: bool = False channel_user_id: str | None = None + authorization_id: str | None = None class MoviePilotApiExecutor: @@ -138,7 +141,7 @@ class MoviePilotApiExecutor: rendered = rendered.replace("{" + name + "}", quote(str(value), safe="")) return rendered - def _build_headers(self) -> dict[str, str]: + def _build_headers(self, operation_id: str | None = None, method: str | None = None, path: str | None = None) -> dict[str, str]: """ 构造宿主令牌和请求上下文头,并确保头值符合 ASCII 约束。 """ @@ -146,7 +149,23 @@ class MoviePilotApiExecutor: if not user_id.isdigit(): raise ApiExecutionError("当前 Agent 身份没有可用于 API 鉴权的用户 ID") username = self._context.username or user_id - if self._context.channel and self._context.channel_user_id and not self._context.public_read_only: + if self._context.authorization_id: + from app.application.security.authorization import get_channel_authorization + + service = get_channel_authorization() + if service is None or not operation_id: + raise ApiExecutionError("渠道授权服务不可用") + try: + user = service.authorize_operation(self._context.authorization_id, operation_id) + except PermissionError as error: + raise ApiExecutionError(str(error)) from error + token = create_access_token( + userid=user.id, username=user.name, super_user=user.is_superuser, + agent_channel=self._context.channel, agent_channel_user=self._context.channel_user_id, + agent_authorization_id=user.authorization_id, agent_operation=operation_id, + agent_method=method, agent_path=path, + ) + elif self._context.channel and self._context.channel_user_id and not self._context.public_read_only: # 渠道发起人写入宿主签名声明而非请求头,外部调用者无法伪造命令回执和会话操作的目标。 token = create_access_token( userid=int(user_id), @@ -241,8 +260,9 @@ class MoviePilotApiExecutor: if operation_id == "search.torrents" else _DEFAULT_API_REQUEST_TIMEOUT_SECONDS ) + headers = await run_agent_blocking("db", self._build_headers, operation_id=operation_id, method=route.method, path=path) if self._context.authorization_id else self._build_headers() request = self._request_factory( - headers=self._build_headers(), + headers=headers, timeout=request_timeout, verify=False, trust_env=False, diff --git a/app/agent/identity.py b/app/agent/identity.py index 8d93c0183..28754f475 100644 --- a/app/agent/identity.py +++ b/app/agent/identity.py @@ -4,6 +4,8 @@ Agent 渠道绑定与自主任务执行账号的解析。 渠道发送者标识只用于绑定查询,执行账号始终使用持久化用户主键。 """ +from typing import cast + from app.agent.tools.base import run_agent_blocking from app.application.security.user import ChainUserRepository, UserSnapshot from app.schemas.types import NotificationChannel @@ -52,6 +54,8 @@ async def require_execution_user( users: ChainUserRepository | None, execution_user_id: int | None, expected_identity: str | None = None, + authorization_id: str | None = None, + capability: str | None = None, ) -> UserSnapshot: """ 按已固定的执行用户主键复核账号,拒绝用户名回收和管理员回退。 @@ -59,9 +63,24 @@ async def require_execution_user( :param users: 宿主用户仓储;未装配时拒绝执行 :param execution_user_id: 固定的用户主键;旧任务为空时须先从原会话更新绑定 :param expected_identity: 固定的账号不可变身份;提供时拒绝主键被新账号复用 + :param authorization_id: 固定的渠道授权身份,存在时重新读取当前角色与能力 + :param capability: 需要复核的渠道能力,普通账号为空 :return: 当前仍然存在且启用的执行用户及实时权限 :raises AgentIdentityError: 身份缺失、账号删除或停用 """ + if authorization_id: + from app.application.security.authorization import get_channel_authorization + + service = get_channel_authorization() + if service is None: + raise AgentIdentityError("渠道授权服务不可用") + try: + user = await run_agent_blocking("db", service.principal, authorization_id, capability=capability) + except PermissionError as error: + raise AgentIdentityError(str(error)) from error + if user.id != execution_user_id or (expected_identity is not None and user.notification_identity != expected_identity): + raise AgentIdentityError("任务执行主体已改变,请从原会话重新创建任务") + return cast(UserSnapshot, user) if execution_user_id is None: raise AgentIdentityError( "任务尚未绑定执行账号,请先确认 MoviePilot 账号的渠道绑定," @@ -89,6 +108,7 @@ async def resolve_task_user( is_admin: bool, execution_user_id: int | None = None, execution_user_identity: str = "", + authorization_id: str | None = None, ) -> UserSnapshot: """ 创建或显式更新旧任务时,将可信入口身份转换为真实用户。 @@ -101,11 +121,21 @@ async def resolve_task_user( :param is_admin: 可信入口注入的管理员标记,仅已认证集成可借用宿主身份 :param execution_user_id: 当前自主任务的固定执行主体;嵌套创建时继续沿用 :param execution_user_identity: 当前自主任务已固定的账号不可变身份 + :param authorization_id: 当前已确认的渠道授权;嵌套任务不能脱离该身份 :return: 唯一启用的真实用户 :raises AgentIdentityError: 无法确定唯一启用用户 """ if execution_user_id is not None: - return await require_execution_user(users, execution_user_id, execution_user_identity) + return await require_execution_user(users, execution_user_id, execution_user_identity, authorization_id, "schedule") + if channel and source and channel not in {NotificationChannel.Web.value, NotificationChannel.WebAgent.value}: + from app.application.security.authorization import get_channel_authorization + + service = get_channel_authorization() + if service is not None: + try: + return cast(UserSnapshot, await run_agent_blocking("db", service.resolve, channel, source, user_id, capability="schedule")) + except PermissionError as error: + raise AgentIdentityError(str(error)) from error integration = source == "api" or ( channel == NotificationChannel.Web.value and source in {"openai", "openai.responses", "anthropic"} diff --git a/app/agent/middleware/policy.py b/app/agent/middleware/policy.py index 8455b24e2..4c20fc6ff 100644 --- a/app/agent/middleware/policy.py +++ b/app/agent/middleware/policy.py @@ -25,6 +25,7 @@ from app.agent.policy.orchestrator import ( ) from app.agent.policy.registry import requests_system_setting_secrets from app.agent.policy.sanitizer import stable_type_name +from app.agent.tools.base import run_agent_blocking from app.agent.tools.catalog import ToolCatalogSnapshot from app.agent.tools.impl.api import MoviePilotApiTool from app.agent.tools.impl.mcp import McpExternalTool @@ -225,6 +226,11 @@ class AgentPolicyMiddleware(AgentMiddleware): """ 执行一次本地工具调用,并复用 ToolNode 的策略生命周期。 """ + authorization_error = await self._channel_authorization_error(tool, arguments) + if authorization_error: + return False, ToolMessage(content=authorization_error, tool_call_id=str(invocation_id or ""), + name=str(getattr(tool, "name", "unknown")), status="error", + additional_kwargs={EXECUTION_OUTCOME_KEY: ExecutionOutcome.FAILED.value}) if self.context.origin is ToolOrigin.SUBAGENT and not self._subagent_read_allowed(tool, arguments): return False, self._subagent_read_only_error(tool, arguments, invocation_id) observation = call_policy_hook( @@ -271,6 +277,37 @@ class AgentPolicyMiddleware(AgentMiddleware): ) return True, result + async def _channel_authorization_error(self, tool: Any, arguments: dict[str, Any]) -> str | None: + """ + 所有本地工具和子代理调用前复核渠道状态,覆盖记忆和外部 MCP 等非基础工具。 + """ + identity = self.context.agent_context.get("authorization_id") + if not isinstance(identity, str) or not identity: + if self.context.agent_context.get("channel_authorization_required") is True: + from app.agent.policy.api import API_UNBOUND_READ_OPERATIONS + + public_operation = isinstance(tool, MoviePilotApiTool) and arguments.get("operation_id") in API_UNBOUND_READ_OPERATIONS + if not public_operation and getattr(tool, "name", "") not in {"send_message", "send_voice_message"}: + return "此操作需要管理员授权,请发送“申请使用”,批准后重新发送要执行的操作。" + return None + from app.application.security.authorization import get_channel_authorization + + service = get_channel_authorization() + if service is None: + return "渠道授权服务不可用,未执行该工具。" + try: + capability = "schedule" if isinstance(self.context.agent_context.get("execution_user_id"), int) else None + user = await run_agent_blocking("db", service.principal, identity, capability=capability) + self.context.agent_context["is_admin"] = user.is_superuser + if not user.is_superuser and (isinstance(tool, McpExternalTool) or str(getattr(tool, "_agent_tool_source", "")).startswith("plugin:")): + return "此扩展工具需要渠道管理员授权。" + return None + except PermissionError as error: + state = self.context.agent_context.setdefault("execution_identity_error", {}) + if isinstance(state, dict): + state["message"] = str(error) + return str(error) + @staticmethod def _subagent_read_allowed(tool: Any, arguments: dict[str, Any]) -> bool: """ diff --git a/app/agent/orchestrator.py b/app/agent/orchestrator.py index 96631ed5d..5d1c32655 100644 --- a/app/agent/orchestrator.py +++ b/app/agent/orchestrator.py @@ -86,6 +86,7 @@ from app.agent.terminal.ownership import ( close_terminal_scope, current_terminal_scope, ) +from app.agent.tools.base import run_agent_blocking from app.agent.tools.catalog import ToolCatalogSnapshot from app.agent.tools.impl.api import MoviePilotApiTool from app.agent.tools.impl.mcp import create_external_mcp_tools @@ -510,8 +511,15 @@ class MoviePilotAgent: ) self._steering_inbox = SteeringInbox(session_id, str(user_id or "")) self._scheduled_terminal_scopes: set[TerminalScope] = set() - learning_dir = agent_runtime_manager.get_user_learning_dir(user_id) - user_memory_dir = agent_runtime_manager.get_user_memory_dir(user_id) + self._memory_owner_id = user_id + if channel and source and channel not in {NotificationChannel.Web.value, NotificationChannel.WebAgent.value}: + from app.application.security.authorization import get_channel_authorization + + authorization = get_channel_authorization() + if authorization is not None: + self._memory_owner_id = authorization.memory_owner(channel, source, str(user_id or "")) + learning_dir = agent_runtime_manager.get_user_learning_dir(self._memory_owner_id) + user_memory_dir = agent_runtime_manager.get_user_memory_dir(self._memory_owner_id) self._learning = LearningSession( session_id=session_id, skill_root=learning_dir / 'skills', memory_root=user_memory_dir, public_roots=(agent_runtime_manager.skills_dir,), on_usage=self._record_review_usage, @@ -523,6 +531,8 @@ class MoviePilotAgent: self.execution_user_id: int | None = None self.execution_user_identity: str | None = None self.is_channel_admin = is_channel_admin + # 定时任务的渠道授权随任务冻结;交互入口每轮按渠道实例重新解析。 + self.authorization_id: str | None = None self.original_message_id = original_message_id self.original_chat_id = original_chat_id self.reply_mode = replay_mode @@ -1081,6 +1091,24 @@ class MoviePilotAgent: 自主任务使用已固定账号的实时权限,内部后台维护仍保留宿主管理员语义。 """ + if self.authorization_id: + from app.application.security.authorization import get_channel_authorization + + authorization = get_channel_authorization() + if authorization is None: + return False + user = await run_agent_blocking("db", authorization.principal, self.authorization_id) + return bool(user.is_superuser) + if self.channel and self.source and self.channel not in {NotificationChannel.Web.value, NotificationChannel.WebAgent.value}: + from app.application.security.authorization import get_channel_authorization + + authorization = get_channel_authorization() + if authorization is not None: + try: + user = await run_agent_blocking("db", authorization.resolve, self.channel, self.source, str(self.user_id or "")) + return bool(user.is_superuser) + except PermissionError: + return False if self.execution_user_id is not None: execution_user = await require_execution_user( self._data.users if self._data is not None else None, self.execution_user_id, @@ -1102,16 +1130,26 @@ class MoviePilotAgent: try: if self._data is None: return False - user = await self._data.users.async_get_by_name(self.username) + local_user = await self._data.users.async_get_by_name(self.username) except Exception as e: logger.error(f"检查 Agent 用户管理员身份失败: {e}") return False - return bool(user and user.is_superuser) + return bool(local_user and local_user.is_superuser) async def _build_tool_context(self, should_dispatch_reply: bool) -> Dict[str, object]: """ 构造本轮工具共享上下文。 """ + authorization_id = self.authorization_id + authorization_required = bool(authorization_id) + if not authorization_id and self.channel and self.source and self.channel not in {NotificationChannel.Web.value, NotificationChannel.WebAgent.value}: + from app.application.security.authorization import get_channel_authorization + + authorization = get_channel_authorization() + if authorization is not None: + authorization_required = True + member = await run_agent_blocking("db", authorization.find, self.channel, self.source, str(self.user_id or "")) + authorization_id = member.id if member and member.status == "approved" else None return { "user_reply_sent": False, "reply_mode": None, @@ -1119,6 +1157,9 @@ class MoviePilotAgent: "is_admin": await self._is_system_admin_context(), "execution_user_id": self.execution_user_id, "execution_user_identity": self.execution_user_identity, + "authorization_id": authorization_id, + "channel_authorization_required": authorization_required, + "memory_owner_id": self._memory_owner_id, "execution_identity_error": {}, "require_secret_confirmation": True, "secret_confirmation_handler": self._register_secret_confirmation, @@ -1916,6 +1957,9 @@ class MoviePilotAgent: "is_admin": bool(self._tool_context.get("is_admin")), "execution_user_id": self.execution_user_id, "execution_user_identity": self.execution_user_identity, + "authorization_id": self._tool_context.get("authorization_id"), + "channel_authorization_required": self._tool_context.get("channel_authorization_required", False), + "memory_owner_id": self._memory_owner_id, "execution_identity_error": self._tool_context.get("execution_identity_error", {}), "require_secret_confirmation": True, }, @@ -1956,6 +2000,9 @@ class MoviePilotAgent: "is_admin": bool(self._tool_context.get("is_admin")), "execution_user_id": self.execution_user_id, "execution_user_identity": self.execution_user_identity, + "authorization_id": self._tool_context.get("authorization_id"), + "channel_authorization_required": self._tool_context.get("channel_authorization_required", False), + "memory_owner_id": self._memory_owner_id, "execution_identity_error": self._tool_context.get("execution_identity_error", {}), }, specs=specs, @@ -2062,7 +2109,7 @@ class MoviePilotAgent: stream_handler=self.stream_handler, ) skill_tools = list(getattr(skills_middleware, "tools", []) or []) - user_memory_dir = agent_runtime_manager.get_user_memory_dir(self.user_id) + user_memory_dir = agent_runtime_manager.get_user_memory_dir(self._memory_owner_id) memory_middleware = MemoryMiddleware( memory_dir=str(agent_runtime_manager.memory_dir), user_memory_dir=str(user_memory_dir) if user_memory_dir else None, @@ -2075,10 +2122,10 @@ class MoviePilotAgent: memory_tools.extend(learning_middleware.tools) recall_service = getattr(self._data, "recall", None) recall_middlewares = [] - if recall_service and build_user_memory_key(self.user_id): + if recall_service and build_user_memory_key(self._memory_owner_id): history_session = await self._recall_session(agent_model) if history_session is not None: - recall_middlewares.append(RecallMiddleware(recall_service, str(self.user_id), history_session)) + recall_middlewares.append(RecallMiddleware(recall_service, str(self._memory_owner_id), history_session)) memory_tools.extend(tool for middleware in recall_middlewares for tool in middleware.tools) policy_context = self._build_policy_context() subagent_middlewares, subagent_task_tools = create_subagent_middlewares( diff --git a/app/agent/policy/registry.py b/app/agent/policy/registry.py index cf353a5cb..c70987d61 100644 --- a/app/agent/policy/registry.py +++ b/app/agent/policy/registry.py @@ -136,7 +136,7 @@ class ToolPolicyRegistry: }.get(action, ActionEffect.UNKNOWN) return ActionPolicy( effect=effect, - required_role=PrincipalRole.SYSTEM_ADMIN, + required_role=required_role, confirmation=(ConfirmationMode.NONE if effect is ActionEffect.SAFE_READ else ConfirmationMode.REQUIRED), recovery=(RecoveryMode.NONE if effect is ActionEffect.SAFE_READ else RecoveryMode.RECONCILE), result_sensitivity=ResultSensitivity.NORMAL, diff --git a/app/agent/session.py b/app/agent/session.py index 51e492b38..2ad999d06 100644 --- a/app/agent/session.py +++ b/app/agent/session.py @@ -121,6 +121,7 @@ class _MessageTask: :param scheduled_run_id: 定时任务持久化运行标识;普通消息任务为 None :param execution_user_id: 宿主已验证的计划任务执行账号;普通会话为 None :param execution_user_identity: 执行账号的不可变身份;普通会话为 None + :param authorization_id: 定时任务冻结的渠道授权身份,交互入口按当前渠道解析 :param steering_status_callback: 报告运行中补充消息处理状态的回调 :ivar steering_inbox: 宿主执行时绑定的补充消息队列,初始为 None,不接受构造输入 :ivar terminal_scope: 宿主装配的终端所有权作用域;定时任务在初始化时绑定 @@ -154,6 +155,7 @@ class _MessageTask: scheduled_run_id: Optional[str] = None execution_user_id: Optional[int] = None execution_user_identity: Optional[str] = None + authorization_id: Optional[str] = None steering_status_callback: Optional[SteeringStatusCallback] = None steering_inbox: Optional[SteeringInbox] = field(default=None, init=False, repr=False) terminal_scope: Optional[TerminalScope] = field(default=None, init=False) @@ -374,6 +376,7 @@ class AgentSessionOwner: scheduled_run_id: Optional[str] = None, execution_user_id: Optional[int] = None, execution_user_identity: Optional[str] = None, + authorization_id: Optional[str] = None, ) -> str: """ 处理用户消息:同渠道的运行中补充输入进入当前上下文,其余消息按会话排队。 @@ -381,6 +384,7 @@ class AgentSessionOwner: :param execution_user_id: 宿主已验证的计划任务执行账号,不由模型或渠道输入指定 :param execution_user_identity: 对应账号的不可变身份,避免删除后的用户主键复用 + :param authorization_id: 本轮定时执行绑定的渠道授权,不接受模型参数覆盖 """ completion_future: Optional[asyncio.Future[str]] = ( asyncio.get_running_loop().create_future() if wait_for_completion else None @@ -411,6 +415,7 @@ class AgentSessionOwner: scheduled_run_id=scheduled_run_id, execution_user_id=execution_user_id, execution_user_identity=execution_user_identity, + authorization_id=authorization_id, ) async with self._lifecycle_lock: if not self._accepting_tasks: @@ -817,6 +822,7 @@ class AgentSessionOwner: # 每轮都覆盖执行主体,防止计划任务与交互消息复用会话时串用权限。 agent.execution_user_id = task.execution_user_id agent.execution_user_identity = task.execution_user_identity + agent.authorization_id = task.authorization_id task.agent = agent inbox = self._session_steering_inboxes.get(session_id) if inbox is None: diff --git a/app/agent/tasks.py b/app/agent/tasks.py index c86e34d9a..c01aad259 100644 --- a/app/agent/tasks.py +++ b/app/agent/tasks.py @@ -14,6 +14,7 @@ from app.agent.middleware.jobs import filter_active_jobs, load_jobs_metadata from app.agent.orchestrator import AGENT_EXECUTION_ERROR_PREFIX, HEARTBEAT_SESSION_PREFIX from app.agent.prompt import prompt_manager from app.agent.runtime import agent_runtime_manager +from app.agent.tools.base import run_agent_blocking from app.application.agenttask import get_agent_task_execution_service from app.chain.agent import AgentChain from app.foundation.identity import SYSTEM_INTERNAL_USER_ID @@ -106,18 +107,36 @@ class AgentTaskOwner(AgentLifecycleOwner): success = True result = "" notification_username = None + sender_id = run.user_id + delivery = None try: + if run.execution_authorization_id: + from app.application.security.authorization import get_channel_authorization + + authorization = get_channel_authorization() + if authorization: + delivery = await run_agent_blocking("db", authorization.delivery, run.execution_authorization_id) + if delivery: + sender_id = delivery[2] + if run.channel and not run.execution_authorization_id: + from app.application.security.authorization import get_channel_authorization + from app.domain.authorization import LEGACY_CHANNELS + + if get_channel_authorization() is not None and run.channel in {item[0] for item in LEGACY_CHANNELS.values()}: + raise AgentIdentityError("此旧任务尚未确认渠道授权,请从原会话删除后重新创建;不会回退其它账号。") user = await require_execution_user( self._data.users if self._data is not None else None, run.execution_user_id, run.execution_user_identity or "", + run.execution_authorization_id, + "schedule", ) notification_username = user.name result = await self.process_message( session_id=run.session_id, - user_id=run.user_id, + user_id=sender_id, message=task_message, - channel=None, - source=None, + channel=delivery[0] if delivery else None, + source=delivery[1] if delivery else None, username=notification_username, original_chat_id=None, reply_mode=ReplyMode.DISPATCH, @@ -126,6 +145,7 @@ class AgentTaskOwner(AgentLifecycleOwner): scheduled_run_id=run.run_id, execution_user_id=user.id, execution_user_identity=user.notification_identity, + authorization_id=run.execution_authorization_id, ) result_text = str(result or "").strip() success = not result_text.startswith( @@ -151,9 +171,9 @@ class AgentTaskOwner(AgentLifecycleOwner): Message.model_validate({ "mtype": MessageType.Agent, "username": notification_username, - "channel": run.channel if isinstance(err, AgentIdentityError) else None, - "source": run.message_source if isinstance(err, AgentIdentityError) else None, - "userid": run.user_id if isinstance(err, AgentIdentityError) else None, + "channel": delivery[0] if delivery else run.channel if isinstance(err, AgentIdentityError) else None, + "source": delivery[1] if delivery else run.message_source if isinstance(err, AgentIdentityError) else None, + "userid": sender_id if delivery or isinstance(err, AgentIdentityError) else None, "original_chat_id": run.original_chat_id if isinstance(err, AgentIdentityError) else None, "title": f"定时任务执行失败:{run.name}", "text": result, diff --git a/app/agent/tools/base.py b/app/agent/tools/base.py index af899a5d7..ac4f06546 100644 --- a/app/agent/tools/base.py +++ b/app/agent/tools/base.py @@ -811,6 +811,19 @@ class MoviePilotTool(BaseTool, metaclass=ABCMeta): :return: 当前调用者是系统管理员、渠道管理员或显式管理员上下文时返回 True """ + authorization_id = self._agent_context.get("authorization_id") + if isinstance(authorization_id, str) and authorization_id: + from app.application.security.authorization import get_channel_authorization + + service = get_channel_authorization() + if service is None: + return False + try: + user = await self.run_blocking("db", service.principal, authorization_id, + capability="schedule" if isinstance(self._agent_context.get("execution_user_id"), int) else None) + return bool(user.is_superuser) + except PermissionError: + return False if "is_admin" in self._agent_context: return self._agent_context.get("is_admin") is True @@ -894,7 +907,7 @@ class MoviePilotTool(BaseTool, metaclass=ABCMeta): runtime_root = agent_root / "runtime" for protected in (runtime_root / 'learning' / 'users', runtime_root / 'history' / 'users', runtime_root / 'code' / 'users'): if self._is_path_relative_to(resolved_path, protected): - user_key = build_user_memory_key(self._user_id) + user_key = build_user_memory_key(str(self._agent_context.get("memory_owner_id") or self._user_id)) if not user_key or not self._is_path_relative_to(resolved_path, protected / user_key): return resolved_path, '抱歉,不能读取或修改其他用户的 Agent 消息和个人技能。' if self._is_path_relative_to(resolved_path, runtime_root) and operation != "读取": @@ -911,7 +924,7 @@ class MoviePilotTool(BaseTool, metaclass=ABCMeta): user_memory_root = memory_root / "users" if self._is_path_relative_to(resolved_path, user_memory_root): - user_key = build_user_memory_key(self._user_id) + user_key = build_user_memory_key(str(self._agent_context.get("memory_owner_id") or self._user_id)) own_memory_root = user_memory_root / user_key if user_key else None if not own_memory_root or not self._is_path_relative_to(resolved_path, own_memory_root): return ( @@ -971,6 +984,19 @@ class MoviePilotTool(BaseTool, metaclass=ABCMeta): Agent 共享上下文中的显式管理员事实优先;没有该事实的旧调用才按渠道 管理员名单回查,并保留无消息渠道内部调用的兼容行为。 """ + authorization_id = self._agent_context.get("authorization_id") + if isinstance(authorization_id, str) and authorization_id: + from app.application.security.authorization import get_channel_authorization + + service = get_channel_authorization() + if service is None: + return "渠道授权服务不可用" + try: + user = await self.run_blocking("db", service.principal, authorization_id, + capability="schedule" if isinstance(self._agent_context.get("execution_user_id"), int) else None) + self._agent_context["is_admin"] = user.is_superuser + except PermissionError as error: + return str(error) if not self._require_admin: return None diff --git a/app/agent/tools/impl/agent_task.py b/app/agent/tools/impl/agent_task.py index e87716a98..1f7d661b9 100644 --- a/app/agent/tools/impl/agent_task.py +++ b/app/agent/tools/impl/agent_task.py @@ -190,6 +190,21 @@ class AgentTaskTool(MoviePilotTool): target = kwargs.get("task_id") or kwargs.get("name") or "" return f"{action_name}自主定时任务:{target}".rstrip(":") + def set_agent_context(self, agent_context: Optional[dict[str, object]]) -> None: + """ + 渠道成员按调度能力管理本人任务,其他入口保留既有管理员要求。 + """ + super().set_agent_context(agent_context) + self._require_admin = not bool(self._agent_context.get("authorization_id")) + + @property + def _task_owner(self) -> str: + """ + 按不可变授权身份隔离任务,避免相同平台 ID 在不同机器人之间串用。 + """ + identity = self._agent_context.get("authorization_id") + return f"channel:{identity}" if identity else str(self._user_id) + @staticmethod def _absolute_trigger(payload: AgentTaskInput) -> str: """ @@ -238,10 +253,11 @@ class AgentTaskTool(MoviePilotTool): trigger_type=payload.trigger_type, cron_expression=(trigger_value if payload.trigger_type == "cron" else None), run_at=trigger_value if payload.trigger_type == "date" else None, - user_id=str(self._user_id), + user_id=self._task_owner, username=user.name, execution_user_id=user.id, execution_user_identity=user.notification_identity, + execution_authorization_id=user.authorization_id, session_id=str(self._session_id), channel=self._channel or (chat.channel if chat else None), source=self._source or (chat.source if chat else None), @@ -267,10 +283,10 @@ class AgentTaskTool(MoviePilotTool): oper = self.data.tasks if task_id is not None: - task = oper.get(task_id=task_id, user_id=str(self._user_id)) + task = oper.get(task_id=task_id, user_id=self._task_owner) tasks = [task] if task else [] else: - tasks = oper.list(user_id=str(self._user_id), enabled=enabled) + tasks = oper.list(user_id=self._task_owner, enabled=enabled) result: list[dict[str, object]] = [] for task in tasks: data = agent_task_to_dict( @@ -283,7 +299,7 @@ class AgentTaskTool(MoviePilotTool): agent_task_run_to_dict(run) for run in oper.list_runs( task_id=task.id, - user_id=str(self._user_id), + user_id=self._task_owner, limit=10, ) ] @@ -307,7 +323,7 @@ class AgentTaskTool(MoviePilotTool): if payload.task_id is None: raise ValueError("update 缺少 task_id") oper = self.data.tasks - task = oper.get(task_id=payload.task_id, user_id=str(self._user_id)) + task = oper.get(task_id=payload.task_id, user_id=self._task_owner) if not task: return None if task.last_status == "running": @@ -367,16 +383,16 @@ class AgentTaskTool(MoviePilotTool): updated = oper.update( task_id=payload.task_id, payload=update_payload, - user_id=str(self._user_id), + user_id=self._task_owner, ) if not updated: - current = oper.get(task_id=payload.task_id, user_id=str(self._user_id)) + current = oper.get(task_id=payload.task_id, user_id=self._task_owner) if current and current.last_status == "running": return {"error": (f"Agent 定时任务 {payload.task_id} 正在执行,请稍后再修改")} return None updated_task = oper.get( task_id=payload.task_id, - user_id=str(self._user_id), + user_id=self._task_owner, ) if updated_task is None: return None @@ -390,7 +406,7 @@ class AgentTaskTool(MoviePilotTool): """ 校验任务归属和状态,返回可执行性及任务名称。 """ - task = self.data.tasks.get(task_id=task_id, user_id=str(self._user_id)) + task = self.data.tasks.get(task_id=task_id, user_id=self._task_owner) if not task: return "not_found", None if not task.enabled: @@ -407,7 +423,7 @@ class AgentTaskTool(MoviePilotTool): deleted = self.data.tasks.delete( task_id=task_id, - user_id=str(self._user_id), + user_id=self._task_owner, ) if deleted: remove_agent_task_job(task_id) @@ -433,6 +449,7 @@ class AgentTaskTool(MoviePilotTool): is_admin=await self.is_admin_user(), execution_user_id=context_id if isinstance(context_id, int) else None, execution_user_identity=str(self._agent_context.get("execution_user_identity") or ""), + authorization_id=str(self._agent_context.get("authorization_id") or "") or None, ) async def _update(self, payload: AgentTaskInput) -> str: @@ -443,7 +460,7 @@ class AgentTaskTool(MoviePilotTool): :return: 更新后的任务或不能更新的明确原因 """ current = await self.run_blocking( - "db", self.data.tasks.get, task_id=payload.task_id, user_id=str(self._user_id), + "db", self.data.tasks.get, task_id=payload.task_id, user_id=self._task_owner, ) identity_payload: dict[str, object] = {} if current is not None and current.execution_user_id is None and payload.enabled is not False: @@ -458,6 +475,7 @@ class AgentTaskTool(MoviePilotTool): identity_payload = { "execution_user_id": user.id, "execution_user_identity": user.notification_identity, + "execution_authorization_id": user.authorization_id, "username": user.name, } task = await self.run_blocking("db", self._update_task, payload, identity_payload) @@ -493,6 +511,18 @@ class AgentTaskTool(MoviePilotTool): delay_minutes=delay_minutes, enabled=enabled, ) + identity = self._agent_context.get("authorization_id") + if isinstance(identity, str) and identity: + from app.application.security.authorization import get_channel_authorization + + service = get_channel_authorization() + if service is None: + return "渠道授权服务不可用" + capability = "schedule" if action in {"create", "run"} or (action == "update" and enabled is not False) else None + try: + await self.run_blocking("db", service.principal, identity, capability=capability) + except PermissionError as error: + return str(error) if payload.action == "create": if not get_runtime_setting("AI_AGENT_ENABLE"): return "AI Agent 未启用,无法创建自主定时任务" diff --git a/app/agent/tools/impl/api.py b/app/agent/tools/impl/api.py index f853dccee..b3920a558 100644 --- a/app/agent/tools/impl/api.py +++ b/app/agent/tools/impl/api.py @@ -285,6 +285,21 @@ class MoviePilotApiTool(MoviePilotTool): 把 Web、渠道或集成身份解析为真实 MoviePilot API 用户身份。 """ raw_user_id = str(self._user_id or "") + from app.application.security.authorization import get_channel_authorization + + authorization = get_channel_authorization() + authorization_id = self._agent_context.get("authorization_id") + if authorization is not None and (authorization_id or (self._channel and self._source and self._channel not in {NotificationChannel.Web.value, NotificationChannel.WebAgent.value})): + try: + if isinstance(authorization_id, str) and authorization_id: + user = await self.run_blocking("db", authorization.principal, authorization_id) + else: + user = await self.run_blocking("db", authorization.resolve, self._channel, self._source, raw_user_id) + self._agent_context["authorization_id"] = user.authorization_id + return str(user.id), user.name, user.is_superuser + except PermissionError as error: + self._record_identity_error(str(error)) + raise ApiExecutionError(str(error)) from error execution_user_id = self._agent_context.get("execution_user_id") if isinstance(execution_user_id, int): try: @@ -402,6 +417,7 @@ class MoviePilotApiTool(MoviePilotTool): channel_user_id=( str(self._user_id) if self._channel and self._user_id and not public_read_only else None ), + authorization_id=str(self._agent_context.get("authorization_id") or "") or None, ) ), is_admin, diff --git a/app/api/dependencies/auth.py b/app/api/dependencies/auth.py index 0488d3bdb..f27b70c44 100644 --- a/app/api/dependencies/auth.py +++ b/app/api/dependencies/auth.py @@ -16,6 +16,7 @@ from app.application.security.auth import ( AuthService, AuthUserRepository, ) +from app.application.security.authorization import get_channel_authorization from app.application.security.passkey import PasskeyRepository, PasskeyService from app.application.security.user import ( UserRepository, @@ -74,6 +75,8 @@ def get_current_user( """ 读取令牌对应用户;主体 ID 缺失或账号不存在时按认证失败处理。 """ + if token_data.agent_authorization_id: + return _channel_principal(token_data) user_repository = cast( AuthUserRepository, runtime.authentication.user_repository(db) ) @@ -95,6 +98,10 @@ async def get_current_user_async( """ 异步读取令牌对应用户;主体 ID 缺失或账号不存在时按认证失败处理。 """ + if token_data.agent_authorization_id: + from app.runtime.execution import run_in_threadpool + + return await run_in_threadpool(_channel_principal, token_data) user_repository = cast( UserRepository, runtime.authentication.user_repository(db) ) @@ -108,6 +115,19 @@ async def get_current_user_async( return user +def _channel_principal(token_data: _SchemaTokenPayload) -> Any: + """ + 为当前请求读取实时渠道权限,不把底层内部账号当作普通网页登录账号。 + """ + service = get_channel_authorization() + if service is None or not token_data.agent_authorization_id or not token_data.agent_operation: + raise HTTPException(status_code=401, detail="渠道授权不可用") + try: + return service.authorize_operation(token_data.agent_authorization_id, token_data.agent_operation) + except PermissionError as error: + raise HTTPException(status_code=403, detail=str(error)) from error + + def get_current_active_user( current_user: Any = Depends(get_current_user), ) -> Any: @@ -148,6 +168,15 @@ def _ensure_manage_user(current_user: Any) -> Any: return current_user +def get_current_download_viewer(current_user: Any = Depends(get_current_active_user)) -> Any: + """ + 渠道成员仅查看自己的下载;普通网页入口继续要求全局管理权限。 + """ + if getattr(current_user, "authorization_id", None) and current_user.permissions.get("download") is True: + return current_user + return _ensure_manage_user(current_user) + + def get_current_active_manage_user( current_user: Any = Depends(get_current_active_user), ) -> Any: diff --git a/app/api/endpoints/authorization.py b/app/api/endpoints/authorization.py new file mode 100644 index 000000000..389a8fe38 --- /dev/null +++ b/app/api/endpoints/authorization.py @@ -0,0 +1,177 @@ +""" +系统管理员管理渠道申请、成员权限和启用状态的端点。 +""" + +from dataclasses import asdict +from typing import Any + +from fastapi import Depends, HTTPException + +from app.api.dependencies.auth import get_current_active_superuser, get_current_active_user +from app.api.response import ResponseAPIRouter +from app.application.notification import get_notification_configs +from app.application.security.authorization import ChannelAuthorizationService, ChannelMember, get_channel_authorization +from app.domain.authorization import LEGACY_CHANNELS +from app.schemas.authorization import ( + AuthorizationChannel as _SchemaAuthorizationChannel, +) +from app.schemas.authorization import ( + ChannelAuthorizationData as _SchemaAuthorizationData, +) +from app.schemas.authorization import ( + ChannelBindingData as _SchemaBindingData, +) +from app.schemas.authorization import ( + ChannelMember as _SchemaChannelMember, +) +from app.schemas.authorization import ( + ChannelMemberCreate as _SchemaMemberCreate, +) +from app.schemas.authorization import ( + ChannelMemberUpdate as _SchemaMemberUpdate, +) +from app.schemas.message import Message +from app.schemas.response import Response as _SchemaResponse +from app.schemas.types import NotificationChannel + +router = ResponseAPIRouter() + + +@router.post("/binding", summary="生成当前账号的渠道关联码", response_model=_SchemaResponse[_SchemaBindingData]) +def create_binding(user: Any = Depends(get_current_active_user)) -> _SchemaResponse[_SchemaBindingData]: + """ + 当前网页账号生成五分钟一次性码,需在本人渠道私聊中提交以验证双方身份。 + """ + if getattr(user, "authorization_id", None) or getattr(user, "account_type", "local") != "local": + raise HTTPException(status_code=403, detail="请登录 MoviePilot 网页账号生成关联码") + code, expires_at = _service().create_binding(user.id) + return _SchemaResponse(success=True, data=_SchemaBindingData(code=code, expires_at=expires_at)) + + +def _service() -> ChannelAuthorizationService: + """ + 读取已装配授权服务,未就绪时按服务不可用返回。 + """ + service = get_channel_authorization() + if service is None: + raise HTTPException(status_code=503, detail="渠道授权服务尚未就绪") + return service + + +def _administrator(user: Any = Depends(get_current_active_superuser)) -> Any: + """ + 仅接受网页登录系统管理员,渠道管理员不能修改公共授权。 + """ + if getattr(user, "authorization_id", None) or getattr(user, "account_type", "local") != "local": + raise HTTPException(status_code=403, detail="请使用 MoviePilot 系统管理员账号管理渠道授权") + return user + + +def _project(member: ChannelMember) -> _SchemaChannelMember: + """ + 只投影管理界面需要的信息,隐藏内部用户主键和不可变凭据身份。 + """ + config = next( + (item for item in get_notification_configs(include_disabled=True) if item.id == member.notification_id), None + ) + values = asdict(member) + values["source"] = config.name if config else "渠道已删除" + values["channel_enabled"] = bool( + config and config.enabled and LEGACY_CHANNELS.get(config.type or "", (None,))[0] == member.channel + ) + values["linked_username"] = _service().linked_username(member) + return _SchemaChannelMember.model_validate(values) + + +@router.get("/", summary="查询渠道成员与待审批申请", response_model=_SchemaResponse[_SchemaAuthorizationData]) +def list_authorizations(_: Any = Depends(_administrator)) -> _SchemaResponse[_SchemaAuthorizationData]: + """ + 返回所有授权记录及脱敏后的渠道选择项。 + """ + channels = [ + _SchemaAuthorizationChannel( + id=item.id, name=item.name or "", channel=LEGACY_CHANNELS[item.type][0], enabled=bool(item.enabled) + ) + for item in get_notification_configs(include_disabled=True) + if item.type in LEGACY_CHANNELS + ] + return _SchemaResponse( + success=True, + data=_SchemaAuthorizationData( + members=[_project(member) for member in _service().list_members()], channels=channels + ), + ) + + +def _notify(member: ChannelMember) -> None: + """ + 在授权事务提交后向原渠道私发状态回执,不重放先前业务操作。 + """ + delivery = _service().delivery(member.id) + if delivery is None: + return + labels = { + "approved": "已授权,请重新发送要执行的操作。", + "rejected": "授权申请未通过,请联系管理员。", + "disabled": "渠道授权已停用,请联系管理员。", + } + from app.chain.message import MessageChain + + MessageChain().post_message( + Message( + channel=NotificationChannel(delivery[0]), + source=delivery[1], + userid=delivery[2], + title=labels[member.status], + save_history=False, + private_delivery=True, + ) + ) + + +@router.put("/{member_id}", summary="审批或修改渠道授权", response_model=_SchemaResponse[_SchemaChannelMember]) +def update_authorization( + member_id: str, payload: _SchemaMemberUpdate, user: Any = Depends(_administrator) +) -> _SchemaResponse[_SchemaChannelMember]: + """ + 由系统管理员批准、拒绝、停用或恢复渠道成员,提交后向原渠道回执。 + """ + try: + member = _service().update( + member_id, status=payload.status, role=payload.role, scopes=tuple(payload.scopes), reviewer_id=user.id + ) + except ValueError as error: + raise HTTPException(status_code=400, detail=str(error)) from error + _notify(member) + return _SchemaResponse(success=True, data=_project(member)) + + +@router.post("/", summary="直接授权指定渠道成员", response_model=_SchemaResponse[_SchemaChannelMember]) +def create_authorization( + payload: _SchemaMemberCreate, user: Any = Depends(_administrator) +) -> _SchemaResponse[_SchemaChannelMember]: + """ + 为已核对的平台用户创建记录并设置权限,不要求成员先申请。 + """ + config = next( + ( + item + for item in get_notification_configs() + if item.id == payload.notification_id and item.type in LEGACY_CHANNELS + ), + None, + ) + if config is None: + raise HTTPException(status_code=400, detail="目标渠道不存在或尚未启用") + service = _service() + member = service.request( + LEGACY_CHANNELS[config.type or ""][0], + config.name or "", + payload.sender_id.strip(), + payload.display_name.strip(), + ) + member = service.update( + member.id, status=payload.status, role=payload.role, scopes=tuple(payload.scopes), reviewer_id=user.id + ) + _notify(member) + return _SchemaResponse(success=True, data=_project(member)) diff --git a/app/api/endpoints/download.py b/app/api/endpoints/download.py index eeca5b3c6..ef45089f5 100644 --- a/app/api/endpoints/download.py +++ b/app/api/endpoints/download.py @@ -8,7 +8,11 @@ import anyio from fastapi import Body, Depends from app.adapters.web.security.access import verify_token -from app.api.dependencies.auth import get_current_active_manage_user, get_current_active_user +from app.api.dependencies.auth import ( + get_current_active_manage_user, + get_current_active_user, + get_current_download_viewer, +) from app.api.dependencies.site import get_site_sync_query_service from app.api.principal import ApiPrincipal from app.api.response import ( @@ -221,11 +225,14 @@ def _resolve_add_media( @router.get("/", summary="正在下载", response_model=List[_SchemaDownloaderTorrent]) -def current(name: Optional[str] = None, _: ApiPrincipal = Depends(get_current_active_manage_user), page: CompatiblePageParam = None, count: CompatibleCountParam = None) -> Any: +def current(name: Optional[str] = None, _: ApiPrincipal = Depends(get_current_download_viewer), page: CompatiblePageParam = None, count: CompatibleCountParam = None) -> Any: """ - 查询全局下载任务,仅向具有管理权限的用户开放。 + 管理员查询全局下载任务,获授权渠道成员仅查询自己发起的任务。 """ - return DownloadChain().downloading(name) + tasks = DownloadChain().downloading(name) + if getattr(_, "authorization_id", None) and not _.is_superuser: + return [task for task in tasks if task.username == _.name] + return tasks @router.post( diff --git a/app/api/endpoints/history.py b/app/api/endpoints/history.py index 5c4004c7c..631a5aaf0 100644 --- a/app/api/endpoints/history.py +++ b/app/api/endpoints/history.py @@ -279,6 +279,19 @@ async def download_history( """ page = page if page is not None else 1 count = count if count is not None else 30 + if isinstance(_, _SchemaTokenPayload) and _.agent_authorization_id: + from app.application.security.authorization import get_channel_authorization + from app.runtime.execution import run_in_threadpool + + authorization = get_channel_authorization() + if authorization is None: + raise HTTPException(status_code=503, detail="渠道授权服务不可用") + user = await run_in_threadpool(authorization.authorize_operation, _.agent_authorization_id, _.agent_operation or "") + username = None if user.is_superuser else user.name + results = await query.list_download(page=page, count=count, username=username) + if response is not None: + response.headers[COLLECTION_TOTAL_HEADER] = str(await query.count_download(username=username)) + return results results = await query.list_download(page=page, count=count) if response is not None: response.headers[COLLECTION_TOTAL_HEADER] = str(await query.count_download()) diff --git a/app/api/endpoints/notification.py b/app/api/endpoints/notification.py index d6965cc4a..49f41b868 100644 --- a/app/api/endpoints/notification.py +++ b/app/api/endpoints/notification.py @@ -74,6 +74,14 @@ def _normalize_configs(value: list[NotificationConf], *, validate_identities: bo data = config.model_dump() data["id"] = identity data["name"] = name + from app.domain.authorization import LEGACY_CHANNELS + + definition = LEGACY_CHANNELS.get(data.get("type") or "") + if definition: + values = dict(data.get("config") or {}) + values.pop(definition[1], None) + values.pop(definition[2], None) + data["config"] = values normalized.append(data) return normalized diff --git a/app/api/routers.py b/app/api/routers.py index 71b8efebc..1da6c3122 100644 --- a/app/api/routers.py +++ b/app/api/routers.py @@ -11,6 +11,7 @@ from app.api.endpoints import ( anilist, anthropic, auth, + authorization, bangumi, classification, dashboard, @@ -68,6 +69,7 @@ class RouterSpec(NamedTuple): API_V1_ROUTER_SPECS: tuple[RouterSpec, ...] = ( RouterSpec(auth.router, "/auth", ("auth",)), + RouterSpec(authorization.router, "/authorization", ("authorization",)), RouterSpec(login.router, "/login", ("login",)), RouterSpec(user.router, "/user", ("user",)), RouterSpec(mfa.router, "/mfa", ("mfa",)), diff --git a/app/application/agenttask.py b/app/application/agenttask.py index 4ad9f51ad..ae951f47d 100644 --- a/app/application/agenttask.py +++ b/app/application/agenttask.py @@ -60,6 +60,7 @@ class AgentTaskSnapshot: :param updated_at: 任务最近更新时间字符串 :param execution_user_id: 固定的真实执行账号主键;旧任务为 None,须显式更新绑定 :param execution_user_identity: 账号不可变身份,防止删除账号后的主键复用 + :param execution_authorization_id: 渠道授权的固定身份;普通网页登录任务为空 """ id: int @@ -84,6 +85,7 @@ class AgentTaskSnapshot: updated_at: str execution_user_id: int | None = None execution_user_identity: str | None = None + execution_authorization_id: str | None = None @dataclass(frozen=True, slots=True) @@ -111,6 +113,7 @@ class AgentTaskRunSnapshot: :param result: 本次运行的结果摘要,尚未产生时为 None :param execution_user_id: 认领时冻结的真实执行账号主键;旧记录为 None :param execution_user_identity: 认领时冻结的账号不可变身份 + :param execution_authorization_id: 本次认领时冻结的渠道授权身份 """ run_id: str @@ -133,6 +136,7 @@ class AgentTaskRunSnapshot: result: str | None execution_user_id: int | None = None execution_user_identity: str | None = None + execution_authorization_id: str | None = None class AgentTaskRepository(Protocol): diff --git a/app/application/history/__init__.py b/app/application/history/__init__.py index c29c8527f..4eea06196 100644 --- a/app/application/history/__init__.py +++ b/app/application/history/__init__.py @@ -393,12 +393,14 @@ class DownloadHistoryQueryPort(Protocol): self, page: int = 1, count: int = 30, + *, username: str | None = None, ) -> list[DownloadHistorySnapshot]: """ 异步按下载时间倒序分页返回历史快照。 :param page: 页码,从 1 开始 :param count: 每页最多返回的记录数 + :param username: 限定业务归属;为空时保留全局查询 :return: 按下载时间倒序排列的当前页历史快照 """ ... @@ -443,20 +445,22 @@ class AsyncDownloadHistoryQueryRepository(Protocol): 下载历史只读用例需要的最小异步持久化端口。 """ - async def async_list_by_page(self, page: int = 1, count: int = 30) -> list[DownloadHistorySnapshot]: + async def async_list_by_page(self, page: int = 1, count: int = 30, *, username: str | None = None) -> list[DownloadHistorySnapshot]: """ 按下载时间倒序分页读取历史记录。 :param page: 页码,从 1 开始 :param count: 每页最多返回的记录数 + :param username: 限定业务归属;为空时查询全部账号 :return: 按下载时间倒序排列的当前页历史快照 """ ... - async def async_count(self) -> int: + async def async_count(self, *, username: str | None = None) -> int: """ 返回下载历史记录总数。 + :param username: 限定业务归属;为空时统计全部账号 :return: 下载历史记录总数 """ ... @@ -578,18 +582,19 @@ class HistoryQueryService: *, page: int = 1, count: int = 30, + username: str | None = None, ) -> list[DownloadHistory]: """ 分页读取下载历史并转换为稳定的接口 DTO。 """ - records = await self._download_repository.async_list_by_page(page, count) + records = await self._download_repository.async_list_by_page(page, count, username=username) if username is not None else await self._download_repository.async_list_by_page(page, count) return [DownloadHistory.model_validate(record) for record in records] - async def count_download(self) -> int: + async def count_download(self, *, username: str | None = None) -> int: """ 返回下载历史精确总数,供分页 API 通过附加元数据报告。 """ - return await self._download_repository.async_count() + return await self._download_repository.async_count(username=username) if username is not None else await self._download_repository.async_count() async def list_transfer( self, diff --git a/app/application/messaging/channel/admin.py b/app/application/messaging/channel/admin.py index 77eebb736..209ab5e74 100644 --- a/app/application/messaging/channel/admin.py +++ b/app/application/messaging/channel/admin.py @@ -48,6 +48,7 @@ def matches_channel_admin( channel: Union[NotificationChannel, str], config: Optional[dict[str, Any]], *principal_ids: Optional[Union[str, int]], + source: str | None = None, ) -> bool: """ 判断任一稳定主体 ID 是否命中渠道登记的管理员集合。 @@ -56,6 +57,20 @@ def matches_channel_admin( channel.value if isinstance(channel, NotificationChannel) else str(channel) ) resolver = _CHANNEL_ADMIN_RESOLVERS.get(channel_value) + # 已装配时统一授权是唯一事实源,不能通过旧名单或接收人绕过撤销。 + from app.application.security.authorization import get_channel_authorization + + service = get_channel_authorization() + if service is not None: + if not source: + from app.application.notification import get_notification_configs + + matches = [item.name for item in get_notification_configs() if item.config == config] + source = matches[0] if len(matches) == 1 else None + return bool(source) and any( + service.is_admin(channel_value, source or "", str(principal_id).strip()) + for principal_id in principal_ids if principal_id is not None + ) if not resolver: return False authorized_ids = { diff --git a/app/application/security/auth.py b/app/application/security/auth.py index 7b4267654..c7f524811 100644 --- a/app/application/security/auth.py +++ b/app/application/security/auth.py @@ -307,11 +307,23 @@ class AuthService: """ 按当前持久化用户状态校验令牌身份与权限声明。 """ + if payload.agent_authorization_id: + from app.application.security.authorization import get_channel_authorization + + service = get_channel_authorization() + if service is None or not payload.agent_operation: + raise PermissionError("渠道授权服务不可用") + channel_user = service.authorize_operation(payload.agent_authorization_id, payload.agent_operation) + if payload.sub != channel_user.id or payload.username != channel_user.name or payload.super_user != channel_user.is_superuser: + raise PermissionError("渠道授权身份或权限已改变,请重试") + return if payload.sub is None: raise PermissionError("用户不存在或已禁用") user = self._users.get_by_id(payload.sub) if not user or not user.is_active: raise PermissionError("用户不存在或已禁用") + if getattr(user, "account_type", "local") != "local": + raise PermissionError("渠道身份不能使用网页登录凭据") if payload.username != user.name or payload.super_user != user.is_superuser: raise PermissionError("令牌身份或权限上下文不匹配") @@ -319,6 +331,8 @@ class AuthService: """ 使用统一逻辑构造登录 Token 响应。 """ + if getattr(user, "account_type", "local") != "local": + raise PermissionError("渠道身份不可网页登录") level = SitesHelper().auth_level config = get_api_runtime_config_snapshot() return _SchemaToken( diff --git a/app/application/security/authorization.py b/app/application/security/authorization.py new file mode 100644 index 000000000..539df506f --- /dev/null +++ b/app/application/security/authorization.py @@ -0,0 +1,400 @@ +""" +渠道成员申请、审批、身份投影和实时权限校验。 + +成员的业务归属由独立身份保存;已有账号关联只通过已验证的双方凭据完成。 +""" + +import hashlib +import secrets +import time +from collections.abc import Callable +from contextlib import AbstractContextManager +from dataclasses import dataclass, replace +from types import MappingProxyType +from typing import Any, Protocol + +from app.application.notification import get_notification_configs +from app.application.security.user import UserSnapshot +from app.domain.authorization import ( + AUTHORIZATION_SCOPES, + CHANNEL_OPERATION_SCOPES, + CHANNEL_PUBLIC_OPERATIONS, + LEGACY_CHANNELS, +) +from app.schemas.system import NotificationConf + + +@dataclass(frozen=True, slots=True) +class ChannelMember: + """ + 脱离数据库会话的渠道成员记录。 + + :param id: 随机且不可变的成员身份 + :param notification_id: 不可变的通知实例 ID + :param channel: 平台渠道名称 + :param sender_id: 平台提供的完整发送者 ID + :param display_name: 仅供展示的昵称,不参与认证 + :param status: pending、approved、rejected 或 disabled + :param role: member 或 admin + :param scopes: 普通成员可用的能力 + :param user_id: 固定的内部业务归属账号 + :param user_identity: 账号不可变身份,不允许主键复用后继承授权 + :param linked_user_id: 已验证关联的网页账号;为空时独立使用 + :param created_at: 首次申请的 UTC Unix 秒 + :param updated_at: 最近修改的 UTC Unix 秒 + :param origin: request、legacy 或 manual,表示记录来源 + :param reviewed_by: 最近修改授权的系统管理员主键,未审批或历史迁移为空 + """ + + id: str + notification_id: str + channel: str + sender_id: str + display_name: str + status: str + role: str + scopes: tuple[str, ...] + user_id: int + user_identity: str + linked_user_id: int | None + created_at: float + updated_at: float + origin: str + reviewed_by: int | None + + +class AuthorizationUnitOfWork(Protocol): + """ + 单次授权操作的独占事务端口,不向用例暴露 ORM。 + """ + + def list_members(self) -> list[ChannelMember]: + """ + 返回全部成员的独立快照。 + + :return: 按申请时间排序的成员列表 + """ + ... + + def get(self, member_id: str) -> ChannelMember | None: + """ + 按随机身份读取成员。 + + :param member_id: 不可变成员 ID + :return: 成员快照;不存在时为空 + """ + ... + + def find(self, notification_id: str, sender_id: str) -> ChannelMember | None: + """ + 精确查找渠道实例内的发送者。 + + :param notification_id: 不可变通知实例 ID + :param sender_id: 完整平台发送者 ID + :return: 唯一成员快照;未登记时为空 + """ + ... + + def request(self, notification_id: str, channel: str, sender_id: str, display_name: str) -> ChannelMember: + """ + 幂等暂存申请,不恢复已被拒绝或停用的成员。 + + :param notification_id: 已校验的通知实例 ID + :param channel: 已校验的渠道名称 + :param sender_id: 完整发送者 ID + :param display_name: 仅展示的昵称 + :return: 新申请或既有记录 + """ + ... + + def update( + self, member_id: str, *, status: str, role: str, scopes: tuple[str, ...], reviewer_id: int + ) -> ChannelMember: + """ + 暂存管理端确认的权限与状态,不更换业务归属。 + + :param member_id: 随机成员 ID + :param status: 合法成员状态 + :param role: 成员或管理员角色 + :param scopes: 经用例校验的能力集合 + :param reviewer_id: 已通过系统管理员认证的操作人主键 + :return: 更新后快照;不存在时抛出 ValueError + """ + ... + + def user(self, user_id: int) -> UserSnapshot | None: + """ + 查询当前业务账号或关联账号。 + + :param user_id: 持久化账号主键 + :return: 当前账号快照;已删除时为空 + """ + ... + + def stage_binding(self, code_hash: str, user: UserSnapshot, expires_at: float) -> None: + """ + 暂存网页账号确认的一次性关联码摘要。 + + :param code_hash: 高熵随机码摘要,不保存原文 + :param user: 当前已认证、启用的网页登录账号 + :param expires_at: UTC Unix 秒,到期后不得消费 + """ + ... + + def consume_binding(self, member_id: str, code_hash: str, now: float) -> ChannelMember: + """ + 原子消费关联码,并将成员本人业务归属合并到已验证网页账号。 + + :param member_id: 已由渠道发送者证明的成员身份 + :param code_hash: 用户在原渠道提交的关联码摘要 + :param now: 用于到期校验的 UTC Unix 秒 + :return: 已关联成员快照;无效、到期、冲突或执行中任务导致 ValueError + """ + ... + + def observe_aliases(self, notification_id: str, sender_id: str, aliases: tuple[str, ...]) -> None: + """ + 只记录同一已验证平台报文中的发送者别名,不合并相互冲突的授权记录。 + + :param notification_id: 已定位的稳定通知实例 + :param sender_id: 报文中的规范发送者 ID + :param aliases: 平台同时提供并证明属于同一人的其它 ID + """ + ... + + def commit(self) -> None: + """ + 提交已暂存的申请或授权;失败时向上传播且不发送成功通知。 + """ + ... + + +AuthorizationScope = Callable[[], AbstractContextManager[AuthorizationUnitOfWork]] + + +class ChannelAuthorizationService: + """ + 在通知实例与发送者范围内管理成员,并向执行边界提供实时身份。 + """ + + def __init__(self, scope: AuthorizationScope) -> None: + """ + 保存启动组合根提供的短事务工厂。 + """ + self._scope = scope + + @staticmethod + def notification(channel: str, source: str) -> NotificationConf: + """ + 按渠道类型和来源名称定位当前启用实例,改名不改变成员归属。 + """ + for config in get_notification_configs(): + definition = LEGACY_CHANNELS.get(config.type or "") + if definition and definition[0] == channel and config.name == source: + return config + raise PermissionError("通知渠道不存在或已停用") + + def memory_owner(self, channel: str, source: str, sender_id: str) -> str: + """ + 用稳定通知实例与平台发送者共同隔离记忆,不与网页登录或其它机器人串用。 + """ + notification = self.notification(channel, source) + return f"channel:{notification.id}:{sender_id}" + + def find(self, channel: str, source: str, sender_id: str) -> ChannelMember | None: + """ + 查询当前启用实例中的稳定发送者,不根据显示名或群 ID 授权。 + """ + notification = self.notification(channel, source) + with self._scope() as transaction: + return transaction.find(notification.id, sender_id) + + def delivery(self, member_id: str) -> tuple[str, str, str] | None: + """ + 按稳定配置身份解析当前私聊投递目标,不把任务结果广播到其它实例。 + """ + with self._scope() as transaction: + member = transaction.get(member_id) + if member is None: + return None + config = next((item for item in get_notification_configs() if item.id == member.notification_id), None) + if config is None or LEGACY_CHANNELS.get(config.type or "", (None,))[0] != member.channel: + return None + return member.channel, config.name or "", member.sender_id + + def linked_username(self, member: ChannelMember) -> str | None: + """ + 返回已验证关联的当前网页账号名,删除或替换后不暴露新账号资料。 + """ + if member.linked_user_id is None: + return None + with self._scope() as transaction: + user = transaction.user(member.linked_user_id) + return user.name if user and user.notification_identity == member.user_identity else None + + def list_members(self) -> list[ChannelMember]: + """ + 列出管理弹窗所需的成员及待审批申请。 + """ + with self._scope() as transaction: + return transaction.list_members() + + def is_admin(self, channel: str, source: str, sender_id: str) -> bool: + """ + 判断发送者在指定启用实例中是否为已批准管理员。 + + :param channel: 通知渠道显示值 + :param source: 实例名称,不能跨实例继承权限 + :param sender_id: 平台稳定发送者 ID + :return: 当前实例内具有有效管理员权限时返回 True + """ + try: + return self.resolve(channel, source, sender_id).is_superuser + except PermissionError: + return False + + def request(self, channel: str, source: str, sender_id: str, display_name: str) -> ChannelMember: + """ + 原子登记申请;重复消息不会增加记录或解除管理员停用。 + """ + if not sender_id: + raise ValueError("缺少渠道发送者 ID") + notification = self.notification(channel, source) + with self._scope() as transaction: + member = transaction.request(notification.id, channel, sender_id, display_name) + transaction.commit() + return member + + def update( + self, member_id: str, *, status: str, role: str, scopes: tuple[str, ...], reviewer_id: int + ) -> ChannelMember: + """ + 校验审批结果并提交;仅由已认证的系统管理员端点调用。 + """ + if status not in {"approved", "rejected", "disabled"} or role not in {"member", "admin"}: + raise ValueError("授权状态或角色不正确") + if not set(scopes).issubset(AUTHORIZATION_SCOPES): + raise ValueError("包含未知的授权能力") + with self._scope() as transaction: + member = transaction.update( + member_id, status=status, role=role, scopes=tuple(sorted(set(scopes))), reviewer_id=reviewer_id + ) + transaction.commit() + return member + + def principal(self, member_id: str, *, capability: str | None = None) -> UserSnapshot: + """ + 每次执行重新检查渠道、成员和关联账号,返回最小有效权限投影。 + + :param member_id: 宿主持久化或签名声明中的成员身份 + :param capability: 额外要求的能力,未指定时仅检查可执行状态 + :return: 业务归属账号与当前有效权限 + :raises PermissionError: 渠道被删停、成员失权或关联账号不可用 + """ + with self._scope() as transaction: + member = transaction.get(member_id) + if member is None or member.status != "approved": + raise PermissionError("渠道成员尚未授权或已停用,请联系管理员") + configs = {config.id: config for config in get_notification_configs()} + config = configs.get(member.notification_id) + if config is None or LEGACY_CHANNELS.get(config.type or "", (None,))[0] != member.channel: + raise PermissionError("通知渠道不存在、已停用或类型已改变") + user = transaction.user(member.user_id) + linked = transaction.user(member.linked_user_id) if member.linked_user_id is not None else None + if ( + user is None + or not user.is_active + or user.notification_identity != member.user_identity + or (member.linked_user_id is not None and (linked is None or not linked.is_active)) + ): + raise PermissionError("渠道成员关联的账号不存在或已停用") + admin = member.role == "admin" and (linked is None or linked.is_superuser) + scopes = set(AUTHORIZATION_SCOPES if admin else member.scopes) + if linked is not None and not linked.is_superuser: + scopes = { + scope + for scope in scopes + if linked.permissions.get( + "subscribe" if scope == "schedule" else "manage" if scope == "download" else scope + ) + is True + } + if capability and not admin and capability not in scopes: + raise PermissionError(f"当前渠道成员未获授权使用此能力:{capability}") + permissions: dict[str, Any] = {scope: scope in scopes for scope in AUTHORIZATION_SCOPES} + permissions.update(discovery=True, manage=False) + return replace( + user, is_superuser=admin, permissions=MappingProxyType(permissions), authorization_id=member.id + ) + + def authorize_operation(self, member_id: str, operation_id: str) -> UserSnapshot: + """ + 为受控 API 重新校验能力,仅管理员可越过普通成员的操作清单。 + """ + user = self.principal(member_id) + if user.is_superuser or operation_id in CHANNEL_PUBLIC_OPERATIONS: + return user + scope = CHANNEL_OPERATION_SCOPES.get(operation_id) + if scope is None or user.permissions.get(scope) is not True: + raise PermissionError("当前渠道成员没有此操作的授权,请联系管理员调整权限") + return user + + def resolve(self, channel: str, source: str, sender_id: str, *, capability: str | None = None) -> UserSnapshot: + """ + 将消息入口身份转换为当前可执行的统一渠道主体。 + """ + member = self.find(channel, source, sender_id) + if member is None: + raise PermissionError("此操作需要授权,请发送“申请使用”,由管理员批准后重试;已有账号可先完成账号绑定") + return self.principal(member.id, capability=capability) + + def create_binding(self, user_id: int) -> tuple[str, float]: + """ + 由已登录用户生成五分钟有效的一次性码,原文不写入数据库或日志。 + """ + code = secrets.token_urlsafe(18) + expires_at = time.time() + 300 + with self._scope() as transaction: + user = transaction.user(user_id) + if user is None or not user.is_active or user.account_type != "local": + raise PermissionError("请先登录有效的 MoviePilot 网页账号") + transaction.stage_binding(hashlib.sha256(code.encode()).hexdigest(), user, expires_at) + transaction.commit() + return code, expires_at + + def bind(self, channel: str, source: str, sender_id: str, display_name: str, code: str) -> ChannelMember: + """ + 由渠道发送者消费网页登录生成的码,关联不自动批准或解除已有停用。 + """ + member = self.request(channel, source, sender_id, display_name) + with self._scope() as transaction: + member = transaction.consume_binding(member.id, hashlib.sha256(code.encode()).hexdigest(), time.time()) + transaction.commit() + return member + + def observe_aliases(self, channel: str, source: str, sender_id: str, *aliases: str | None) -> None: + """ + 由可信平台适配器补齐历史 ID 别名,前端和模型参数不能调用此身份证明入口。 + """ + notification = self.notification(channel, source) + with self._scope() as transaction: + transaction.observe_aliases(notification.id, sender_id, tuple(value for value in aliases if value)) + transaction.commit() + + +_configured_service: ChannelAuthorizationService | None = None + + +def configure_channel_authorization(service: ChannelAuthorizationService | None) -> None: + """ + 由启动组合根登记服务;传空值在关闭或测试退出时撤销。 + """ + global _configured_service + _configured_service = service + + +def get_channel_authorization() -> ChannelAuthorizationService | None: + """ + 读取当前生命周期的服务,未装配时返回空值并由调用边界拒绝新能力。 + """ + return _configured_service diff --git a/app/application/security/token.py b/app/application/security/token.py index 07bf7e091..7a7a3d029 100644 --- a/app/application/security/token.py +++ b/app/application/security/token.py @@ -82,6 +82,10 @@ def create_access_token( purpose: Optional[str] = "authentication", agent_channel: Optional[str] = None, agent_channel_user: Optional[str] = None, + agent_authorization_id: Optional[str] = None, + agent_operation: Optional[str] = None, + agent_method: Optional[str] = None, + agent_path: Optional[str] = None, ) -> str: """ 创建带身份、权限等级和用途声明的 JWT 访问令牌。 @@ -97,6 +101,10 @@ def create_access_token( :param purpose: 令牌用途,authentication 或 resource :param agent_channel: 宿主 Agent 会话所属的消息渠道 :param agent_channel_user: 发起该会话的用户在渠道内的原始标识 + :param agent_authorization_id: 统一渠道授权的不可变身份,存在时必须提供固定操作与路径 + :param agent_operation: 已通过授权检查的受控操作 + :param agent_method: 当前 API 请求的固定方法 + :param agent_path: 当前 API 请求的固定路径 :return: 已签名的 JWT 字符串 :raises ValueError: 自定义有效期不是正数 """ @@ -130,6 +138,11 @@ def create_access_token( if purpose == "authentication" and agent_channel and agent_channel_user: payload["agent_channel"] = agent_channel payload["agent_channel_user"] = agent_channel_user + if agent_authorization_id: + if purpose != "authentication" or not all((agent_operation, agent_method, agent_path)): + raise ValueError("渠道凭据必须限定到一次受控 API 操作") + payload.update(agent_authorization_id=agent_authorization_id, agent_operation=agent_operation, + agent_method=agent_method, agent_path=agent_path) encoded: str = jwt.encode(payload, secret_key, algorithm=ALGORITHM) return encoded diff --git a/app/application/security/user.py b/app/application/security/user.py index 901b5bd9d..8864078d4 100644 --- a/app/application/security/user.py +++ b/app/application/security/user.py @@ -60,6 +60,8 @@ class UserSnapshot: :param permissions: 用户权限的只读快照 :param settings: 用户个性化设置的只读快照 :param notification_identity: 不可变的通知绑定身份,不从客户端设置中读取 + :param account_type: local 为网页登录账号,channel 为不可登录的内部渠道归属 + :param authorization_id: 本次执行使用的渠道授权身份,普通网页登录为空 """ id: int @@ -72,6 +74,8 @@ class UserSnapshot: permissions: Mapping[str, FrozenJson] settings: Mapping[str, FrozenJson] notification_identity: str = "" + account_type: str = "local" + authorization_id: str | None = None @classmethod def build( @@ -87,6 +91,7 @@ class UserSnapshot: permissions: Optional[Mapping[str, Any]], settings: Optional[Mapping[str, Any]], notification_identity: str = "", + account_type: str = "local", ) -> "UserSnapshot": """ 复制持久化字段并构造不可变的公开用户快照。 @@ -102,6 +107,7 @@ class UserSnapshot: permissions=_freeze_mapping(permissions), settings=_freeze_mapping(settings), notification_identity=notification_identity, + account_type=account_type, ) diff --git a/app/chain/message.py b/app/chain/message.py index 30e1f27e9..fc0dc453f 100644 --- a/app/chain/message.py +++ b/app/chain/message.py @@ -37,6 +37,7 @@ from app.application.messaging.session import MessageSessionService from app.application.messaging.site import site_interaction_manager from app.application.messaging.skill import SkillInteractionHandler, skill_interaction_manager from app.application.messaging.subscribe import subscribe_interaction_manager +from app.application.security.authorization import get_channel_authorization from app.chain.base import ChainBase from app.chain.interaction import MediaInteractionChain as _MediaInteractionChain from app.chain.site import SiteChain @@ -48,7 +49,7 @@ from app.runtime.loop import main_loop_registry from app.runtime.tasks import get_task_registry from app.schemas.message import IncomingMessage, Message from app.schemas.notification import ChannelCapabilityManager -from app.schemas.types import EventType, NotificationChannel +from app.schemas.types import EventType, MessageType, NotificationChannel class MessageResponsePort(Protocol): @@ -327,6 +328,8 @@ class MessageChain(ChainBase): """ text = text or "" images = IncomingMessage.MessageImage.normalize_list(images) + if self._handle_channel_authorization(channel, source, userid, username, text, callback_data): + return # 兼容归一化:结构化回调优先,CALLBACK: 文本前缀作为旧渠道和插件直接调用的兼容入口 normalized_callback = str(callback_data or "").strip() or None @@ -378,6 +381,11 @@ class MessageChain(ChainBase): ): return + authorization = get_channel_authorization() + channel_managed = authorization is not None and channel not in {NotificationChannel.Web, NotificationChannel.WebAgent} + if channel_managed and authorization is not None: + is_channel_admin = authorization.is_admin(channel.value, source, str(userid)) + interaction_context = InteractionContext( channel=channel, source=source, @@ -387,8 +395,14 @@ class MessageChain(ChainBase): original_chat_id=original_chat_id, is_channel_admin=is_channel_admin, ) + member_result = self._handle_channel_member_message( + interaction_context, text, normalized_callback, images, files, has_audio_input, + ) if channel_managed else None + if member_result is not None: + processing_finish_deferred = member_result + return - if self._plugin_input_interaction_handler().handle_text( + if (not channel_managed or is_channel_admin) and self._plugin_input_interaction_handler().handle_text( context=interaction_context, text=text, reply_to_message_id=reply_to_message_id, @@ -456,6 +470,98 @@ class MessageChain(ChainBase): original_chat_id=original_chat_id, ) + def _handle_channel_member_message( + self, context: InteractionContext, text: str, callback_data: Optional[str], + images: Optional[List[IncomingMessage.MessageImage]], files: Optional[List[IncomingMessage.MessageAttachment]], + has_audio_input: bool, + ) -> Optional[bool]: + """ + 普通及待审批成员只进入受控 Agent,旧管理会话不能在撤权后消费文本。 + + :param context: 平台消息上下文及刚复核的管理员标记 + :param text: 转写后的本次输入 + :param callback_data: 仅批准的 Agent 选项回调交给后续路由 + :param images: 归一化图片附件 + :param files: 文件附件 + :param has_audio_input: 是否已有语音输入 + :return: None 表示继续原路由;布尔值表示本次已处理及是否延后结束状态 + """ + if context.is_channel_admin or callback_data is not None: + return None + if not self.runtime_config.ai_agent_enable: + self.post_message(Message(channel=context.channel, source=context.source, userid=context.user_id, + title="AI Agent 未启用,请联系管理员。", save_history=False)) + return False + if not (self.runtime_config.ai_agent_global or self._has_ai_prefix(text) + or is_agent_learning_command(text) or images or files or has_audio_input): + self.post_message(Message(channel=context.channel, source=context.source, userid=context.user_id, + title="请使用 /ai 加上要执行的操作。", save_history=False)) + return False + return self._handle_ai_message( + text=text, channel=context.channel, source=context.source or "", userid=context.user_id, + username=context.username or "", is_channel_admin=False, original_message_id=context.original_message_id, + original_chat_id=context.original_chat_id, images=images, files=files, has_audio_input=has_audio_input, + ) + + def _handle_channel_authorization( + self, channel: NotificationChannel, source: str, userid: Union[str, int], + username: str, text: str, callback_data: Optional[str], + ) -> bool: + """ + 在语音、传统交互和 Agent 执行前处理申请并统一检查渠道成员状态。 + + 未授权身份只收到申请入口,不自动执行原业务请求。已授权普通成员不能执行传统管理命令。 + """ + service = get_channel_authorization() + if service is None or channel in {NotificationChannel.Web, NotificationChannel.WebAgent}: + return False + value = (callback_data or text).strip() + if value.startswith("CALLBACK:"): + value = value[9:].strip() + try: + member = service.find(channel.value, source, str(userid)) + if value.startswith("绑定账号 "): + member = service.bind(channel.value, source, str(userid), username, value[5:].strip()) + self.post_message(Message(channel=channel, source=source, userid=userid, + title="账号已关联。" + ("请重新发送要执行的操作。" if member.status == "approved" else "渠道权限仍需管理员批准。"), save_history=False, private_delivery=True)) + return True + if value in {"绑定账号", "authorization:bind"}: + self.post_message(Message(channel=channel, source=source, userid=userid, + title="请登录 MoviePilot,打开个人信息 → 账号绑定 → 生成关联码,在此私聊发送“绑定账号 关联码”。", save_history=False, private_delivery=True)) + return True + if value.casefold() in {"申请使用", "/申请使用", "/apply", "authorization:apply"}: + first_request = member is None + member = service.request(channel.value, source, str(userid), username) + labels = {"approved": "你已获得授权,请重新发送要执行的操作。", "pending": "申请已提交,请等待管理员审批。", + "disabled": "当前授权已停用,请联系管理员。", "rejected": "申请未通过,请联系管理员。"} + self.post_message(Message(channel=channel, source=source, userid=userid, + title=labels[member.status], save_history=False)) + if member.status == "pending" and first_request: + self.post_message(Message(mtype=MessageType.Agent, + title="有新的渠道授权申请", text=f"{username} · {source}\n请打开用户管理右下角的渠道授权处理。", save_history=False)) + return True + if member is None or member.status != "approved": + if member is None or member.status == "pending": + if self.runtime_config.ai_agent_enable and not text.startswith("/") and (self.runtime_config.ai_agent_global or self._has_ai_prefix(text)): + # 公共资料继续允许查询,业务 API 仍在执行边界要求已批准授权。 + return False + self.post_message(Message( + channel=channel, source=source, userid=userid, title="此操作需要管理员授权", + text="点击申请使用,或发送“申请使用”。批准后重新发送要执行的操作。", + buttons=[[{"text": "申请使用", "callback_data": "authorization:apply"}, {"text": "绑定已有账号", "callback_data": "authorization:bind"}]], save_history=False, + )) + return True + principal = service.principal(member.id) + traditional_command = value.startswith("/") and not self._has_ai_prefix(value) and not is_agent_learning_command(value) + traditional_callback = bool(callback_data or text.startswith("CALLBACK:")) and parse_agent_choice_callback(value) is None + if (traditional_command or traditional_callback) and not principal.is_superuser: + self.post_message(Message(channel=channel, source=source, userid=userid, title="此命令需要管理员授权。", save_history=False)) + return True + return False + except (PermissionError, ValueError) as error: + self.post_message(Message(channel=channel, source=source, userid=userid, title=str(error), save_history=False)) + return True + def _handle_secret_confirmation_control( self, channel: NotificationChannel, diff --git a/app/db/adapters/agent.py b/app/db/adapters/agent.py index 88e25e683..6b2b5acf9 100644 --- a/app/db/adapters/agent.py +++ b/app/db/adapters/agent.py @@ -60,6 +60,7 @@ def _project_task(record: object) -> AgentTaskSnapshot: username=getattr(record, "username", None), execution_user_id=getattr(record, "execution_user_id", None), execution_user_identity=getattr(record, "execution_user_identity", None), + execution_authorization_id=getattr(record, "execution_authorization_id", None), session_id=session_id, channel=getattr(record, "channel", None), source=getattr(record, "source", None), @@ -114,6 +115,7 @@ def _project_run(record: object) -> AgentTaskRunSnapshot: username=getattr(record, "username", None), execution_user_id=getattr(record, "execution_user_id", None), execution_user_identity=getattr(record, "execution_user_identity", None), + execution_authorization_id=getattr(record, "execution_authorization_id", None), session_id=session_id, channel=getattr(record, "channel", None), message_source=getattr(record, "message_source", None), diff --git a/app/db/adapters/authorization.py b/app/db/adapters/authorization.py new file mode 100644 index 000000000..4bd4b19c3 --- /dev/null +++ b/app/db/adapters/authorization.py @@ -0,0 +1,135 @@ +""" +统一渠道授权端口的短事务与不可变快照适配。 +""" + +from collections.abc import Callable, Iterator +from contextlib import contextmanager + +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import Session + +from app.application.security.authorization import AuthorizationUnitOfWork, ChannelMember +from app.application.security.user import UserSnapshot +from app.db.adapters.user import SqlAlchemyUserRepository +from app.db.models.authorization import ChannelAuthorization +from app.db.oper.authorization import ChannelAuthorizationOper + + +def _snapshot(row: ChannelAuthorization) -> ChannelMember: + """ + 在 Session 关闭前复制成员身份、状态和能力。 + """ + return ChannelMember( + id=row.id, + notification_id=row.notification_id, + channel=row.channel, + sender_id=row.sender_id, + display_name=row.display_name, + status=row.status, + role=row.role, + scopes=tuple(row.scopes), + user_id=row.user_id, + user_identity=row.user_identity, + linked_user_id=row.linked_user_id, + created_at=row.created_at, + updated_at=row.updated_at, + origin=row.origin, + reviewed_by=row.reviewed_by, + ) + + +class SqlAlchemyAuthorizationUnitOfWork: + """ + 为一个同步授权用例持有私有 Session,事务由应用服务显式提交。 + """ + + def __init__(self, session: Session) -> None: + """ + 绑定本作用域 Session 与表级 Oper。 + """ + self._session = session + self._members = ChannelAuthorizationOper(session) + + def list_members(self) -> list[ChannelMember]: + """ + 返回按申请时间排序的脱离会话快照。 + """ + return [_snapshot(row) for row in self._members.list()] + + def get(self, member_id: str) -> ChannelMember | None: + """ + 返回指定成员快照,不保留 ORM 引用。 + """ + row = self._members.get(member_id) + return _snapshot(row) if row else None + + def find(self, notification_id: str, sender_id: str) -> ChannelMember | None: + """ + 读取通知实例内唯一匹配的发送者。 + """ + row = self._members.find(notification_id, sender_id) + return _snapshot(row) if row else None + + def request(self, notification_id: str, channel: str, sender_id: str, display_name: str) -> ChannelMember: + """ + 暂存申请并复制数据库生成的内部归属主键。 + """ + return _snapshot(self._members.request(notification_id, channel, sender_id, display_name)) + + def update( + self, member_id: str, *, status: str, role: str, scopes: tuple[str, ...], reviewer_id: int + ) -> ChannelMember: + """ + 暂存权限变动后返回独立快照。 + """ + return _snapshot( + self._members.update(member_id, status=status, role=role, scopes=scopes, reviewer_id=reviewer_id) + ) + + def user(self, user_id: int) -> UserSnapshot | None: + """ + 读取业务归属或已绑定网页账号的当前状态。 + """ + return SqlAlchemyUserRepository(self._session).get_by_id(user_id) + + def stage_binding(self, code_hash: str, user: UserSnapshot, expires_at: float) -> None: + """ + 仅把随机码摘要、已认证账号和到期时间写入当前事务。 + """ + self._members.stage_binding(code_hash, user.id, user.notification_identity, expires_at) + + def consume_binding(self, member_id: str, code_hash: str, now: float) -> ChannelMember: + """ + 原子消费关联码并返回合并归属后的成员快照。 + """ + try: + return _snapshot(self._members.consume_binding(member_id, code_hash, now)) + except IntegrityError as error: + raise ValueError("账号关联存在业务归属冲突,原数据未修改,请联系管理员核对后重试") from error + + def observe_aliases(self, notification_id: str, sender_id: str, aliases: tuple[str, ...]) -> None: + """ + 将平台证明的同人标识交给表级 Oper 暂存,不对业务账号执行合并。 + """ + self._members.observe_aliases(notification_id, sender_id, aliases) + + def commit(self) -> None: + """ + 提交完整授权事务;失败时由作用域退出回滚。 + """ + self._session.commit() + + +@contextmanager +def authorization_scope(session_factory: Callable[[], Session]) -> Iterator[AuthorizationUnitOfWork]: + """ + 为单次授权创建私有 Session,离开时回滚所有未提交操作并释放资源。 + + :param session_factory: 启动组合根提供的独立 Session 工厂 + :yields: 当前用例可查询、暂存并提交的授权事务端口 + """ + with session_factory() as session: + try: + yield SqlAlchemyAuthorizationUnitOfWork(session) + finally: + session.rollback() diff --git a/app/db/adapters/history/download.py b/app/db/adapters/history/download.py index 95d0ded87..cdb503efd 100644 --- a/app/db/adapters/history/download.py +++ b/app/db/adapters/history/download.py @@ -244,6 +244,7 @@ class TransactionalDownloadHistoryRepository: self, page: int = 1, count: int = 30, + *, username: str | None = None, ) -> list[DownloadHistorySnapshot]: """ 在独立异步 Session 内分页读取并投影历史。 @@ -252,15 +253,16 @@ class TransactionalDownloadHistoryRepository: records = await DownloadHistoryOper(session).async_list_by_page( page, count, + username=username, ) return [_project_history(record) for record in records] - async def async_count(self) -> int: + async def async_count(self, *, username: str | None = None) -> int: """ 在独立异步 Session 内统计下载历史总数。 """ async with self._async_session() as session: - return await DownloadHistoryOper(session).async_count() + return await DownloadHistoryOper(session).async_count(username=username) def add( self, @@ -315,6 +317,7 @@ class SessionDownloadHistoryRepository: self, page: int = 1, count: int = 30, + *, username: str | None = None, ) -> list[DownloadHistorySnapshot]: """ 在请求异步 Session 内分页读取并投影历史。 @@ -324,16 +327,17 @@ class SessionDownloadHistoryRepository: records = await DownloadHistoryOper(self._session).async_list_by_page( page, count, + username=username, ) return [_project_history(record) for record in records] - async def async_count(self) -> int: + async def async_count(self, *, username: str | None = None) -> int: """ 在请求异步 Session 内统计下载历史总数。 """ if not isinstance(self._session, AsyncSession): raise RuntimeError("下载历史异步统计需要 AsyncSession") - return await DownloadHistoryOper(self._session).async_count() + return await DownloadHistoryOper(self._session).async_count(username=username) def stage_delete_history(self, history_id: int) -> None: """ diff --git a/app/db/adapters/user.py b/app/db/adapters/user.py index 94bf535ef..bfec68368 100644 --- a/app/db/adapters/user.py +++ b/app/db/adapters/user.py @@ -44,6 +44,7 @@ def _to_snapshot(model: User) -> UserSnapshot: permissions=model.permissions, settings=model.settings, notification_identity=model.notification_identity or "", + account_type=model.account_type, ) @@ -114,7 +115,7 @@ class SqlAlchemyUserRepository(UserRepository): 在异步请求会话中按可选窗口读取冻结用户快照。 """ session = self._require_async_session() - statement = select(User).order_by(User.id) + statement = select(User).where(User.account_type == "local").order_by(User.id) if page is not None and count is not None: statement = statement.offset((page - 1) * count).limit(count) result = await session.execute(statement) @@ -125,7 +126,7 @@ class SqlAlchemyUserRepository(UserRepository): 在异步请求会话中返回用户精确总数。 """ session = self._require_async_session() - result = await session.execute(select(func.count()).select_from(User)) + result = await session.execute(select(func.count()).select_from(User).where(User.account_type == "local")) return int(result.scalar_one()) async def async_get_by_name(self, name: str) -> Optional[UserSnapshot]: @@ -180,6 +181,8 @@ class SqlAlchemyUserRepository(UserRepository): model = await self._locked_user(session, user_id, payload) if model is None: return None + if model.account_type != "local": + raise ValueError("渠道身份请在渠道授权中管理") old_name = model.name new_name = str(payload.get("name", old_name)) values = {key: value for key, value in payload.items() if key != "id"} @@ -202,6 +205,8 @@ class SqlAlchemyUserRepository(UserRepository): model = await self._locked_user(session, user_id, None) if model is None: return None + if model.account_type != "local": + raise ValueError("渠道身份请在渠道授权中管理") username: str = model.name await session.delete(model) await session.flush() @@ -318,7 +323,7 @@ class TransactionalUserRepository(ChainUserRepository): """ with self._sync_session() as session: model = UserOper(db=session).get_by_name(name) - return _to_auth_snapshot(model) if model else None + return _to_auth_snapshot(model) if model and model.account_type == "local" else None async def async_get_by_name(self, name: str) -> Optional[UserSnapshot]: """ diff --git a/app/db/models/__init__.py b/app/db/models/__init__.py index b354719b8..5794eae8a 100644 --- a/app/db/models/__init__.py +++ b/app/db/models/__init__.py @@ -77,6 +77,7 @@ def load_all_models() -> None: """ 显式导入全部 ORM 模型,供建表和 Alembic 元数据收集使用。 """ + import_module("app.db.models.authorization") for module_name, _ in dict.fromkeys(_MODEL_EXPORTS.values()): import_module(module_name) diff --git a/app/db/models/agenttask.py b/app/db/models/agenttask.py index 2bb8065ea..2f95b17e1 100644 --- a/app/db/models/agenttask.py +++ b/app/db/models/agenttask.py @@ -67,6 +67,8 @@ class AgentTask(Base): execution_user_id: Mapped[Optional[int]] = mapped_column(Integer) # 防止 SQLite 自增主键在删除账号后被另一个账号复用 execution_user_identity: Mapped[Optional[str]] = mapped_column(String(32)) + # 渠道授权主体随定义固定,后台运行不得脱离该授权提升权限。 + execution_authorization_id: Mapped[Optional[str]] = mapped_column(String(32)) session_id: Mapped[str] = mapped_column(String, nullable=False) channel: Mapped[Optional[str]] = mapped_column(String) source: Mapped[Optional[str]] = mapped_column(String) diff --git a/app/db/models/agenttaskrun.py b/app/db/models/agenttaskrun.py index 8c1502070..5784315b9 100644 --- a/app/db/models/agenttaskrun.py +++ b/app/db/models/agenttaskrun.py @@ -36,6 +36,8 @@ class AgentTaskRun(Base): execution_user_id: Mapped[Optional[int]] = mapped_column(Integer) # 账号不可变身份随本次认领冻结,不能通过修改任务影响运行中的主体 execution_user_identity: Mapped[Optional[str]] = mapped_column(String(32)) + # 本次认领时冻结的渠道授权身份,执行时复核当前权限。 + execution_authorization_id: Mapped[Optional[str]] = mapped_column(String(32)) session_id: Mapped[str] = mapped_column(String, nullable=False) channel: Mapped[Optional[str]] = mapped_column(String) message_source: Mapped[Optional[str]] = mapped_column(String) @@ -91,6 +93,7 @@ class AgentTaskRun(Base): AgentTask.username, AgentTask.execution_user_id, AgentTask.execution_user_identity, + AgentTask.execution_authorization_id, AgentTask.session_id, AgentTask.channel, AgentTask.source, @@ -113,6 +116,7 @@ class AgentTaskRun(Base): username=claimed["username"], execution_user_id=claimed["execution_user_id"], execution_user_identity=claimed["execution_user_identity"], + execution_authorization_id=claimed["execution_authorization_id"], session_id=claimed["session_id"], channel=claimed["channel"], message_source=claimed["source"], diff --git a/app/db/models/authorization.py b/app/db/models/authorization.py new file mode 100644 index 000000000..5f3310d5d --- /dev/null +++ b/app/db/models/authorization.py @@ -0,0 +1,60 @@ +""" +统一渠道成员身份、申请状态和授权范围的 ORM 记录。 +""" + +from sqlalchemy import JSON, Float, Index, Integer, String +from sqlalchemy.orm import Mapped, mapped_column + +from app.db.base import Base + + +class ChannelAuthorization(Base): + """ + 按不可变通知实例与平台发送者唯一隔离的授权记录。 + """ + + __tablename__ = "channelauthorization" + # 随机成员身份,不随昵称或渠道改名变化。 + id: Mapped[str] = mapped_column(String(32), primary_key=True) + # 不可变通知配置身份,不对显示名称建立关联。 + notification_id: Mapped[str] = mapped_column(String(128), nullable=False) + # 平台渠道名称与完整发送者标识。 + channel: Mapped[str] = mapped_column(String(64), nullable=False) + sender_id: Mapped[str] = mapped_column(String(256), nullable=False) + # 昵称只供管理员核对,不参与认证。 + display_name: Mapped[str] = mapped_column(String(256), nullable=False) + # 申请、批准、拒绝和停用状态。 + status: Mapped[str] = mapped_column(String(16), nullable=False) + # 成员或管理员角色及普通成员能力集合。 + role: Mapped[str] = mapped_column(String(16), nullable=False) + scopes: Mapped[list[str]] = mapped_column(JSON, nullable=False) + # 固定业务归属与可选的已验证网页登录账号。 + user_id: Mapped[int] = mapped_column(Integer, nullable=False) + # 业务账号不可变身份,防止删除后主键复用继承旧授权。 + user_identity: Mapped[str] = mapped_column(String(32), nullable=False) + linked_user_id: Mapped[int | None] = mapped_column(Integer) + # 仅由平台已验证报文登记的同一发送者别名,如飞书 user_id 与 open_id。 + aliases: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list) + # 审计时间使用 UTC Unix 秒,来源用于解释旧名单迁移。 + created_at: Mapped[float] = mapped_column(Float, nullable=False) + updated_at: Mapped[float] = mapped_column(Float, nullable=False) + origin: Mapped[str] = mapped_column(String(16), nullable=False) + # 最近审批或变更权限的系统管理员主键,旧迁移记录为空。 + reviewed_by: Mapped[int | None] = mapped_column(Integer) + + __table_args__ = (Index("ux_channel_authorization_sender", "notification_id", "sender_id", unique=True),) + + +class ChannelBinding(Base): + """ + 网页账号发起的短时一次性渠道关联凭据,只保存随机码摘要。 + """ + + __tablename__ = "channelbinding" + # 随机码 SHA-256 摘要,原文只在生成时返回给已登录用户。 + id: Mapped[str] = mapped_column(String(64), primary_key=True) + # 网页端确认的本地账号及不可变身份。 + user_id: Mapped[int] = mapped_column(Integer, nullable=False) + user_identity: Mapped[str] = mapped_column(String(32), nullable=False) + # UTC Unix 秒,到期或消费后不可再关联任何渠道。 + expires_at: Mapped[float] = mapped_column(Float, nullable=False) diff --git a/app/db/models/downloadhistory.py b/app/db/models/downloadhistory.py index dee8dd777..e4aa9659a 100644 --- a/app/db/models/downloadhistory.py +++ b/app/db/models/downloadhistory.py @@ -169,13 +169,16 @@ class DownloadHistory(Base): @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, *, username: str | None = None, ) -> list[Self]: """ 异步按时间和主键倒序分页读取下载历史。 """ + statement = select(cls) + if username is not None: + statement = statement.where(cls.username == username) result = await db.execute( - select(cls) + statement .order_by(cls.date.desc(), cls.id.desc()) .offset((page - 1) * count) .limit(count) @@ -201,11 +204,14 @@ class DownloadHistory(Base): return list(result.scalars().all()) @classmethod - async def async_count(cls, db: AsyncSession) -> int: + async def async_count(cls, db: AsyncSession, *, username: str | None = None) -> int: """ 异步统计下载历史总数,空表返回零。 """ - result = await db.execute(select(func.count(cls.id))) + statement = select(func.count(cls.id)) + if username is not None: + statement = statement.where(cls.username == username) + result = await db.execute(statement) count: int = result.scalar() return count diff --git a/app/db/models/user.py b/app/db/models/user.py index c33e9a5bc..6073acb3e 100644 --- a/app/db/models/user.py +++ b/app/db/models/user.py @@ -23,6 +23,8 @@ class User(Base): id = get_id_column() # 用户名,唯一值 name: Mapped[str] = mapped_column(String, nullable=False) + # 渠道内部身份不接受任何网页登录或账号管理操作。 + account_type: Mapped[str] = mapped_column(String(16), nullable=False, default="local", server_default="local") # 邮箱 email: Mapped[Optional[str]] = mapped_column(String) # 加密后密码 diff --git a/app/db/oper/agenttask.py b/app/db/oper/agenttask.py index 180efe319..ef07a80ae 100644 --- a/app/db/oper/agenttask.py +++ b/app/db/oper/agenttask.py @@ -160,6 +160,7 @@ class AgentTaskOper(DbOper): "last_result", "execution_user_id", "execution_user_identity", + "execution_authorization_id", "username", } } diff --git a/app/db/oper/authorization.py b/app/db/oper/authorization.py new file mode 100644 index 000000000..328e9c823 --- /dev/null +++ b/app/db/oper/authorization.py @@ -0,0 +1,195 @@ +""" +渠道成员的会话内查询、申请去重和权限暂存。 +""" + +import time +from typing import cast +from uuid import uuid4 + +from sqlalchemy import delete, select, update +from sqlalchemy.orm import Session + +from app.db.models.authorization import ChannelAuthorization, ChannelBinding +from app.db.models.systemconfig import SystemConfig +from app.db.models.user import User +from app.domain.authorization import CHANNEL_BINDINGS, DEFAULT_MEMBER_SCOPES +from app.schemas.types import SystemConfigKey + + +class ChannelAuthorizationOper: + """ + 使用调用方持有的 Session,不提交事务或发送消息。 + """ + + def __init__(self, session: Session) -> None: + """ + 保存当前独占事务的同步 Session。 + """ + self._session = session + + def list(self) -> list[ChannelAuthorization]: + """ + 按申请时间逆序返回全部授权记录。 + """ + return list( + self._session.scalars(select(ChannelAuthorization).order_by(ChannelAuthorization.created_at.desc())) + ) + + def get(self, member_id: str) -> ChannelAuthorization | None: + """ + 按不可变随机身份查询成员。 + """ + return cast(ChannelAuthorization | None, self._session.get(ChannelAuthorization, member_id)) + + def find(self, notification_id: str, sender_id: str) -> ChannelAuthorization | None: + """ + 精确匹配实例内发送者及平台证明的别名,不跨实例匹配。 + """ + rows = self._session.scalars( + select(ChannelAuthorization).where(ChannelAuthorization.notification_id == notification_id) + ) + matches = [row for row in rows if row.sender_id == sender_id or sender_id in (row.aliases or [])] + return matches[0] if len(matches) == 1 else None + + def request(self, notification_id: str, channel: str, sender_id: str, display_name: str) -> ChannelAuthorization: + """ + 暂存唯一申请及不可登录的内部归属;新关联必须另行验证双方身份。 + """ + # 配置行的数据库锁覆盖查重与新增;多进程并发申请不会留下重复记录或孤立账号。 + self._session.execute( + update(SystemConfig).where(SystemConfig.key == SystemConfigKey.Notifications.value).values(id=SystemConfig.id) + ) + existing = self.find(notification_id, sender_id) + if existing is not None: + return existing + keys = CHANNEL_BINDINGS.get(channel, ()) + identity = uuid4().hex + user = User( + name=f"channel_{identity}", + account_type="channel", + is_active=True, + is_superuser=False, + hashed_password=None, + notification_identity=uuid4().hex, + settings={keys[0]: sender_id} if keys else {}, + permissions={}, + ) + self._session.add(user) + self._session.flush() + now = time.time() + member = ChannelAuthorization( + id=identity, + notification_id=notification_id, + channel=channel, + sender_id=sender_id, + display_name=display_name or sender_id, + status="pending", + role="member", + scopes=list(DEFAULT_MEMBER_SCOPES), + user_id=user.id, + user_identity=user.notification_identity, + linked_user_id=None, + aliases=[], + created_at=now, + updated_at=now, + origin="request", + reviewed_by=None, + ) + self._session.add(member) + self._session.flush() + return member + + def update( + self, member_id: str, *, status: str, role: str, scopes: tuple[str, ...], reviewer_id: int + ) -> ChannelAuthorization: + """ + 暂存状态及能力变化,保留身份和业务归属。 + """ + member = self.get(member_id) + if member is None: + raise ValueError("渠道成员不存在") + member.status, member.role, member.scopes = status, role, list(scopes) + member.updated_at = time.time() + member.reviewed_by = reviewer_id + self._session.flush() + return member + + def stage_binding(self, code_hash: str, user_id: int, user_identity: str, expires_at: float) -> None: + """ + 暂存唯一关联码摘要,生成新码时撤销该网页账号的旧码。 + """ + self._session.execute(delete(ChannelBinding).where(ChannelBinding.user_id == user_id)) + self._session.add( + ChannelBinding(id=code_hash, user_id=user_id, user_identity=user_identity, expires_at=expires_at) + ) + self._session.flush() + + def consume_binding(self, member_id: str, code_hash: str, now: float) -> ChannelAuthorization: + """ + 消费验证码并迁移本人订阅和下载归属;运行中的任务与归属冲突拒绝合并。 + """ + from app.db.models.agenttask import AgentTask + from app.db.models.downloadhistory import DownloadHistory + from app.db.models.subscribe import Subscribe + from app.db.models.subscribehistory import SubscribeHistory + + claim = self._session.execute( + delete(ChannelBinding) + .where(ChannelBinding.id == code_hash, ChannelBinding.expires_at > now) + .returning(ChannelBinding.user_id, ChannelBinding.user_identity) + ).first() + if claim is None: + raise ValueError("关联码无效、已使用或已过期,请在 MoviePilot 中重新生成") + member = self.get(member_id) + user = self._session.get(User, claim.user_id) + if ( + member is None + or user is None + or not user.is_active + or user.account_type != "local" + or user.notification_identity != claim.user_identity + ): + raise ValueError("关联账号已失效,请重新登录后生成关联码") + if member.linked_user_id is not None and member.linked_user_id != user.id: + raise ValueError("此渠道身份已关联其它账号,请先联系管理员核对") + if self._session.scalar( + select(AgentTask.id) + .where(AgentTask.execution_authorization_id == member.id, AgentTask.last_status == "running") + .limit(1) + ): + raise ValueError("此成员仍有执行中的任务,请等待任务结束后重新关联") + previous = self._session.get(User, member.user_id) + if previous is None or previous.notification_identity != member.user_identity: + raise ValueError("原业务归属已失效,无法关联") + if previous.account_type == "channel" and previous.id != user.id: + for model in (Subscribe, SubscribeHistory, DownloadHistory): + # 使用 ORM 属性更新,让订阅身份键等写入不变量一并重新计算。 + for record in self._session.scalars(select(model).where(model.username == previous.name)): + record.username = user.name + self._session.flush() + self._session.execute( + update(AgentTask) + .where(AgentTask.execution_authorization_id == member.id) + .values( + username=user.name, execution_user_id=user.id, execution_user_identity=user.notification_identity + ) + ) + member.user_id = user.id + member.user_identity = user.notification_identity + member.linked_user_id = user.id + member.updated_at = now + self._session.flush() + return member + + def observe_aliases(self, notification_id: str, sender_id: str, aliases: tuple[str, ...]) -> None: + """ + 在单事务内为唯一历史成员登记平台别名,冲突时拒绝合并权限。 + """ + values = {sender_id, *aliases} + matches = {member.id: member for value in values if (member := self.find(notification_id, value)) is not None} + if len(matches) > 1: + raise ValueError("平台发送者 ID 对应多条授权,请管理员在渠道授权中核对") + if matches: + member = next(iter(matches.values())) + member.aliases = sorted(set(member.aliases or []) | (values - {member.sender_id})) + self._session.flush() diff --git a/app/db/oper/downloadhistory.py b/app/db/oper/downloadhistory.py index 5454b4966..e74afe769 100644 --- a/app/db/oper/downloadhistory.py +++ b/app/db/oper/downloadhistory.py @@ -331,21 +331,22 @@ class DownloadHistoryOper(DbOper): self, page: int = 1, count: int = 30, + *, username: str | None = None, ) -> List[DownloadHistory]: """ 异步分页查询下载历史。 """ return await self._execute_async_query( lambda session: DownloadHistory.async_list_by_page( - session, page, count + session, page, count, username=username, ) ) - async def async_count(self) -> int: + async def async_count(self, *, username: str | None = None) -> int: """ 异步统计全部下载历史记录。 """ - count = await self._execute_async_query(DownloadHistory.async_count) + count = await self._execute_async_query(lambda session: DownloadHistory.async_count(session, username=username)) return int(count or 0) async def async_delete_history(self, historyid: int) -> None: diff --git a/app/domain/authorization.py b/app/domain/authorization.py new file mode 100644 index 000000000..bb4116a9f --- /dev/null +++ b/app/domain/authorization.py @@ -0,0 +1,121 @@ +""" +通知渠道授权的旧配置映射与权限范围。 + +旧投递接收人只在升级时用于保留已有管理员身份,运行时不再据此授权。 +""" + +from collections.abc import Mapping +from typing import Any + +from app.schemas.types import NotificationChannel + +# 类型、渠道、旧普通用户键、旧管理员键和升级时保留的主用户键。 +LEGACY_CHANNELS = { + "telegram": (NotificationChannel.Telegram.value, "TELEGRAM_USERS", "TELEGRAM_ADMINS", "TELEGRAM_CHAT_ID"), + "wechat": (NotificationChannel.Wechat.value, "", "WECHAT_ADMINS", "WECHAT_BOT_CHAT_ID"), + "wechatclawbot": ( + NotificationChannel.WechatClawBot.value, + "", + "WECHATCLAWBOT_ADMINS", + "WECHATCLAWBOT_DEFAULT_TARGET", + ), + "feishu": (NotificationChannel.Feishu.value, "", "FEISHU_ADMINS", "FEISHU_OPEN_ID"), + "qqbot": (NotificationChannel.QQ.value, "", "QQBOT_ADMINS", "QQ_OPENID"), + "discord": (NotificationChannel.Discord.value, "", "DISCORD_ADMINS", ""), + "slack": (NotificationChannel.Slack.value, "", "SLACK_ADMINS", ""), + "vocechat": (NotificationChannel.VoceChat.value, "", "VOCECHAT_ADMINS", ""), + "synologychat": (NotificationChannel.SynologyChat.value, "", "SYNOLOGYCHAT_ADMINS", ""), +} + +# 新成员默认拥有的业务能力;定时任务和管理员能力必须单独授予。 +DEFAULT_MEMBER_SCOPES = ("search", "subscribe", "download") +# 授权系统接受的完整能力集合,管理员拥有全部能力。 +AUTHORIZATION_SCOPES = (*DEFAULT_MEMBER_SCOPES, "schedule") +# 原账号绑定字段用于升级时找到原业务归属,不使用昵称推断账号。 +CHANNEL_BINDINGS = { + NotificationChannel.Telegram.value: ("telegram_userid",), + NotificationChannel.Wechat.value: ("wechat_userid",), + NotificationChannel.WechatClawBot.value: ("wechatclawbot_userid",), + NotificationChannel.Feishu.value: ("feishu_userid", "feishu_openid"), + NotificationChannel.QQ.value: ("qq_userid", "qq_openid"), + NotificationChannel.Discord.value: ("discord_userid",), + NotificationChannel.Slack.value: ("slack_userid",), + NotificationChannel.VoceChat.value: ("vocechat_userid",), + NotificationChannel.SynologyChat.value: ("synologychat_userid",), +} + +# 普通渠道成员仅开放明确审计过的数据归属操作,其余能力由管理员执行。 +CHANNEL_OPERATION_SCOPES = { + "media.recognize": "search", + "search.torrents": "search", + "download.add": "download", + "download.artist_collection": "download", + "download.history.list": "download", + "download.tasks.active": "download", + "download.clients": "download", + "download.paths": "download", + "subscription.add": "subscribe", + "subscription.update": "subscribe", + "subscription.search": "subscribe", + "subscription.list": "subscribe", + "subscription.get": "subscribe", + "subscription.find": "subscribe", + "subscription.history": "subscribe", + "subscription.delete": "subscribe", + "subscription.delete_by_media": "subscribe", + "subscription.status.update": "subscribe", + "subscription.reset": "subscribe", + "subscription.files": "subscribe", + "subscription.execution.list": "subscribe", + "subscription.execution.get": "subscribe", + "subscription.execution.cancel": "subscribe", +} + +# 已审计的公共资料查询,已授权成员也可以在固定自身身份下读取。 +CHANNEL_PUBLIC_OPERATIONS = frozenset( + { + "media.search", + "media.person.search", + "media.person.credits", + "media.episode_schedule", + "media.detail", + "media.episode_groups", + "media.episode_group.seasons", + "media.seasons", + "music.recognize", + "music.explore", + "music.album.get", + "music.album.related", + "music.artist.get", + "music.artist.albums", + "music.artist.related", + "recommendation.list", + "subscription.shares", + "subscription.popular", + "subscription.share.statistics", + "plugin.statistics", + } +) + + +def split_principals(value: Any) -> set[str]: + """ + 解析历史逗号分隔名单,保留完整稳定 ID 并去重。 + """ + return {item.strip() for item in str(value or "").split(",") if item.strip()} + + +def legacy_principals(channel_type: str, config: Mapping[str, Any]) -> dict[str, str]: + """ + 投影单个旧渠道实例的角色;同一成员同时命中时保留管理员权限。 + """ + definition = LEGACY_CHANNELS.get(channel_type) + if definition is None: + return {} + _, users_key, admins_key, primary_key = definition + members = dict.fromkeys(split_principals(config.get(users_key)), "member") + admins = split_principals(config.get(admins_key)) + if primary_key and (channel_type != "wechat" or config.get("WECHAT_MODE", "app") == "bot"): + admins.update(split_principals(config.get(primary_key))) + members.update(dict.fromkeys(admins, "admin")) + return members diff --git a/app/locales/en-US.json b/app/locales/en-US.json index 211f98108..110a85e5f 100644 --- a/app/locales/en-US.json +++ b/app/locales/en-US.json @@ -650,7 +650,12 @@ "登记路径必须为不含父目录跳转的绝对路径": "Registration paths must be absolute and cannot contain parent-directory traversal.", "登记字段不能包含控制字符": "Registration fields cannot contain control characters.", "源文件与目标文件不能是同一地址": "The source and destination cannot have the same address.", - "电影登记不能包含季集信息": "Movie registration cannot include season or episode information." + "电影登记不能包含季集信息": "Movie registration cannot include season or episode information.", + "请登录 MoviePilot 网页账号生成关联码": "Sign in to a MoviePilot web account to generate a linking code", + "渠道授权服务尚未就绪": "The channel authorization service is not ready", + "请使用 MoviePilot 系统管理员账号管理渠道授权": "Use a MoviePilot system administrator account to manage channel authorization", + "目标渠道不存在或尚未启用": "The target channel does not exist or is disabled", + "渠道授权服务不可用": "The channel authorization service is unavailable" }, "message_patterns": [ { diff --git a/app/locales/zh-CN.json b/app/locales/zh-CN.json index 15a36b085..ea09a3148 100644 --- a/app/locales/zh-CN.json +++ b/app/locales/zh-CN.json @@ -201,7 +201,12 @@ "Redis连接失败,请检查配置": "Redis连接失败,请检查配置", "TheMovieDb 识别缓存不存在": "TheMovieDb 识别缓存不存在", "TheMovieDb 识别缓存删除成功": "TheMovieDb 识别缓存删除成功", - "TheMovieDb 识别缓存清理完成": "TheMovieDb 识别缓存清理完成" + "TheMovieDb 识别缓存清理完成": "TheMovieDb 识别缓存清理完成", + "请登录 MoviePilot 网页账号生成关联码": "请登录 MoviePilot 网页账号生成关联码", + "渠道授权服务尚未就绪": "渠道授权服务尚未就绪", + "请使用 MoviePilot 系统管理员账号管理渠道授权": "请使用 MoviePilot 系统管理员账号管理渠道授权", + "目标渠道不存在或尚未启用": "目标渠道不存在或尚未启用", + "渠道授权服务不可用": "渠道授权服务不可用" }, "message_patterns": [ { diff --git a/app/locales/zh-TW.json b/app/locales/zh-TW.json index 66edaf284..a3a7ddf22 100644 --- a/app/locales/zh-TW.json +++ b/app/locales/zh-TW.json @@ -598,7 +598,12 @@ "登记路径必须为不含父目录跳转的绝对路径": "登記路徑必須是不含上層目錄跳轉的絕對路徑", "登记字段不能包含控制字符": "登記欄位不能包含控制字元", "源文件与目标文件不能是同一地址": "來源檔案與目標檔案不能是同一位址", - "电影登记不能包含季集信息": "電影登記不能包含季集資訊" + "电影登记不能包含季集信息": "電影登記不能包含季集資訊", + "请登录 MoviePilot 网页账号生成关联码": "請登入 MoviePilot 網頁帳號產生關聯碼", + "渠道授权服务尚未就绪": "渠道授權服務尚未就緒", + "请使用 MoviePilot 系统管理员账号管理渠道授权": "請使用 MoviePilot 系統管理員帳號管理渠道授權", + "目标渠道不存在或尚未启用": "目標渠道不存在或尚未啟用", + "渠道授权服务不可用": "渠道授權服務無法使用" }, "message_patterns": [ { diff --git a/app/modules/_base/notification.py b/app/modules/_base/notification.py index c41cccede..f8423fe38 100644 --- a/app/modules/_base/notification.py +++ b/app/modules/_base/notification.py @@ -45,6 +45,11 @@ class _MessageChannelModuleBase(_ModuleBase, _MessageBase[TService]): """ 判断命令或命令型按钮回调是否应因非管理员身份被拒绝。 """ + from app.application.security.authorization import get_channel_authorization + + if get_channel_authorization() is not None: + # 申请命令在统一消息入口处理,其余传统命令也在该入口检查管理员角色。 + return False if not self._get_admins(config): return False # 模块实例未初始化时 self._channel 为空,退回静态子类型声明 diff --git a/app/modules/discord/__init__.py b/app/modules/discord/__init__.py index fc7f1878d..da2e68afc 100644 --- a/app/modules/discord/__init__.py +++ b/app/modules/discord/__init__.py @@ -187,7 +187,7 @@ class DiscordModule(_MessageChannelModuleBase[Discord]): username=username, is_channel_admin=matches_channel_admin( NotificationChannel.Discord, client_config.config, userid - ), + , source=client_config.name), text=f"CALLBACK:{callback_data}", is_callback=True, callback_data=callback_data, @@ -221,7 +221,7 @@ class DiscordModule(_MessageChannelModuleBase[Discord]): username=username, is_channel_admin=matches_channel_admin( NotificationChannel.Discord, client_config.config, userid - ), + , source=client_config.name), text=text, chat_id=str(chat_id) if chat_id else None, images=images, diff --git a/app/modules/feishu/feishu.py b/app/modules/feishu/feishu.py index 04b8b4ac4..24a1d6204 100644 --- a/app/modules/feishu/feishu.py +++ b/app/modules/feishu/feishu.py @@ -105,6 +105,10 @@ class Feishu: """ 判断飞书命令或命令型按钮回调是否应因非管理员身份被拒绝。 """ + from app.application.security.authorization import get_channel_authorization + + if get_channel_authorization() is not None: + return False if not self._admins: return False return not matches_channel_admin( @@ -606,6 +610,15 @@ class Feishu: userid = open_id or user_id if not userid: return None + from app.application.security.authorization import get_channel_authorization + + authorization = get_channel_authorization() + if authorization is not None: + try: + authorization.observe_aliases(NotificationChannel.Feishu.value, self._name, str(userid), open_id, user_id) + except (PermissionError, ValueError) as error: + logger.warning(f"飞书渠道发送者身份无法确认:{error}") + return None if message.get("type") == "cardAction": callback_data = message.get("callback_data") @@ -634,6 +647,7 @@ class Feishu: }, open_id, user_id, + source=self._name, ), text=f"CALLBACK:{callback_data}", is_callback=True, @@ -680,6 +694,7 @@ class Feishu: }, open_id, user_id, + source=self._name, ), text=text, message_id=message.get("message_id"), diff --git a/app/modules/qqbot/module.py b/app/modules/qqbot/module.py index f43a03396..da169cd9e 100644 --- a/app/modules/qqbot/module.py +++ b/app/modules/qqbot/module.py @@ -194,7 +194,7 @@ class QQBotModule(_MessageChannelModuleBase[QQBot]): NotificationChannel.QQ, client_config.config, user_openid, - ), + source=client_config.name), text=content, images=images, audio_refs=audio_refs, @@ -225,7 +225,7 @@ class QQBotModule(_MessageChannelModuleBase[QQBot]): NotificationChannel.QQ, client_config.config, member_openid, - ), + source=client_config.name), text=content, images=images, audio_refs=audio_refs, diff --git a/app/modules/slack/__init__.py b/app/modules/slack/__init__.py index f90280d43..6ff01c273 100644 --- a/app/modules/slack/__init__.py +++ b/app/modules/slack/__init__.py @@ -186,7 +186,7 @@ class SlackModule(_MessageChannelModuleBase[Slack]): username=username, is_channel_admin=matches_channel_admin( NotificationChannel.Slack, client_config.config, userid - ), + , source=client_config.name), text=text, is_callback=True, callback_data=callback_data, @@ -243,7 +243,7 @@ class SlackModule(_MessageChannelModuleBase[Slack]): username=username, is_channel_admin=matches_channel_admin( NotificationChannel.Slack, client_config.config, userid - ), + , source=client_config.name), text=text, message_id=message_id, chat_id=chat_id, diff --git a/app/modules/synologychat/__init__.py b/app/modules/synologychat/__init__.py index 2189fa4a9..642644569 100644 --- a/app/modules/synologychat/__init__.py +++ b/app/modules/synologychat/__init__.py @@ -181,7 +181,7 @@ class SynologyChatModule(_MessageChannelModuleBase[SynologyChat]): NotificationChannel.SynologyChat, client_config.config, user_id, - ), text=text or "", + source=client_config.name), text=text or "", images=images, audio_refs=audio_refs, files=files) except Exception as err: logger.debug(f"解析SynologyChat消息失败:{str(err)}") diff --git a/app/modules/telegram/module.py b/app/modules/telegram/module.py index 2f0b04e9b..5b0173d52 100644 --- a/app/modules/telegram/module.py +++ b/app/modules/telegram/module.py @@ -186,7 +186,7 @@ class TelegramModule(_MessageChannelModuleBase[Telegram]): NotificationChannel.Telegram, client_config.config, user_id, - ), + source=client_config.name), text=callback_text, is_callback=True, callback_data=callback_data, @@ -250,6 +250,10 @@ class TelegramModule(_MessageChannelModuleBase[Telegram]): ) user_list = (client_config.config or {}).get("TELEGRAM_USERS") + from app.application.security.authorization import get_channel_authorization + + if get_channel_authorization() is not None: + user_list = None if cleaned_text and cleaned_text.startswith("/"): if self._should_reject_admin_command(client_config.config, user_id): @@ -274,7 +278,7 @@ class TelegramModule(_MessageChannelModuleBase[Telegram]): NotificationChannel.Telegram, client_config.config, user_id, - ), + source=client_config.name), text=cleaned_text, message_id=message_id, chat_id=str(chat_id) if chat_id else None, diff --git a/app/modules/vocechat/__init__.py b/app/modules/vocechat/__init__.py index 299b948b9..1514c984c 100644 --- a/app/modules/vocechat/__init__.py +++ b/app/modules/vocechat/__init__.py @@ -175,7 +175,7 @@ class VoceChatModule(_MessageChannelModuleBase[VoceChat]): is_channel_admin=matches_channel_admin( NotificationChannel.VoceChat, client_config.config, from_uid, actor_userid, - ), text=text or "", + source=client_config.name), text=text or "", images=images, audio_refs=audio_refs, files=files) except Exception as err: logger.error(f"VoceChat消息处理发生错误:{str(err)}") diff --git a/app/modules/wechat/__init__.py b/app/modules/wechat/__init__.py index 4907c64a4..b817fe599 100644 --- a/app/modules/wechat/__init__.py +++ b/app/modules/wechat/__init__.py @@ -242,7 +242,7 @@ class WechatModule(_MessageChannelModuleBase[WeChat | WeChatBot]): NotificationChannel.Wechat, client_config.config, user_id, - ), text=content or "", + source=client_config.name), text=content or "", images=images, audio_refs=audio_refs, files=files) except Exception as err: logger.error(f"微信消息处理发生错误:{str(err)}") @@ -326,7 +326,7 @@ class WechatModule(_MessageChannelModuleBase[WeChat | WeChatBot]): NotificationChannel.Wechat, client_config.config, sender, - ), + source=client_config.name), text=text or "", images=images, audio_refs=audio_refs, diff --git a/app/modules/wechat/wechatbot.py b/app/modules/wechat/wechatbot.py index 7ac9dbdaa..93624ab39 100644 --- a/app/modules/wechat/wechatbot.py +++ b/app/modules/wechat/wechatbot.py @@ -670,6 +670,7 @@ class WeChatBot: "WECHAT_MODE": "bot", }, sender, + source=self._config_name, ) if text and text.startswith("/") and self._admins and not is_channel_admin: self.send_msg(title="只有管理员才有权限执行此命令", userid=sender) diff --git a/app/modules/wechatclawbot/__init__.py b/app/modules/wechatclawbot/__init__.py index 1c2a0ea37..d77832ee1 100644 --- a/app/modules/wechatclawbot/__init__.py +++ b/app/modules/wechatclawbot/__init__.py @@ -392,7 +392,7 @@ class WechatClawBotModule(_MessageChannelModuleBase[WechatClawBot]): NotificationChannel.WechatClawBot, config, user_id, - ) + source=client_config.name) if is_admin_command and admins and not is_channel_admin: client = self.get_instance(client_config.name) if client: diff --git a/app/runtime/log.py b/app/runtime/log.py index 1f370bf86..3490197e8 100644 --- a/app/runtime/log.py +++ b/app/runtime/log.py @@ -1139,6 +1139,9 @@ class LoggerManager: except (TypeError, ValueError): formatted_msg = f"{formatted_msg} {' '.join(str(arg) for arg in args)}" + # 渠道关联码属于一次性认证凭据;入站 SDK 可能记录完整消息,所有日志出口前统一隐藏。 + formatted_msg = re.sub(r"(绑定账号\s+)[A-Za-z0-9_-]{20,}", r"\1[已隐藏]", formatted_msg) + file_exc_info = _normalize_exc_info(kwargs.get("exc_info")) if scope: diff --git a/app/schemas/authorization.py b/app/schemas/authorization.py new file mode 100644 index 000000000..1c7fbfe25 --- /dev/null +++ b/app/schemas/authorization.py @@ -0,0 +1,82 @@ +""" +渠道授权管理 API 的输入和输出合同。 +""" + +from typing import Literal, cast + +from pydantic import BaseModel, Field + + +class ChannelMember(BaseModel): + """ + 管理员弹窗展示的成员和申请,不暴露内部登录凭据。 + """ + + id: str = Field(description="不可变渠道成员身份") + notification_id: str = Field(description="不可变通知实例 ID") + channel: str = Field(description="平台渠道名称") + source: str = Field(description="当前通知实例显示名称,实例删除后保留原身份提示") + sender_id: str = Field(description="完整平台发送者 ID") + display_name: str = Field(description="仅用于核对的昵称") + status: Literal["pending", "approved", "rejected", "disabled"] = Field(description="审批与启用状态") + role: Literal["member", "admin"] = Field(description="普通成员或管理员") + scopes: list[str] = Field(description="搜索、订阅、下载和定时任务能力集合") + linked_username: str | None = Field(default=None, description="已验证关联的网页账号名称") + origin: str = Field(description="request 为申请,legacy 为旧名单迁移,manual 为手工授权") + created_at: float = Field(description="首次登记的 UTC Unix 秒") + updated_at: float = Field(description="最近权限变动的 UTC Unix 秒") + channel_enabled: bool = Field(description="通知实例当前是否存在且启用") + + +class ChannelMemberUpdate(BaseModel): + """ + 系统管理员明确提交的审批结果和权限。 + """ + + status: Literal["approved", "rejected", "disabled"] = Field(description="批准、拒绝或停用") + role: Literal["member", "admin"] = Field(default="member", description="角色;管理员必须由界面单独确认") + scopes: list[Literal["search", "subscribe", "download", "schedule"]] = Field( + default_factory=lambda: cast( + list[Literal["search", "subscribe", "download", "schedule"]], ["search", "subscribe", "download"] + ), + description="普通成员可用能力", + ) + + +class ChannelMemberCreate(ChannelMemberUpdate): + """ + 管理员直接添加一个已核对的渠道发送者。 + """ + + notification_id: str = Field(min_length=1, max_length=128, description="目标通知实例稳定 ID") + sender_id: str = Field(min_length=1, max_length=256, description="完整平台发送者 ID,不能使用群 ID 或昵称") + display_name: str = Field(default="", max_length=256, description="管理员备注的显示名称") + + +class AuthorizationChannel(BaseModel): + """ + 授权弹窗可选的通知实例,不包含渠道密钥或连接参数。 + """ + + id: str = Field(description="不可变通知实例 ID") + name: str = Field(description="通知实例名称") + channel: str = Field(description="平台渠道名称") + enabled: bool = Field(description="实例是否启用") + + +class ChannelAuthorizationData(BaseModel): + """ + 渠道授权弹窗首次加载的数据。 + """ + + members: list[ChannelMember] = Field(description="成员与待审批记录") + channels: list[AuthorizationChannel] = Field(description="可管理的通知实例") + + +class ChannelBindingData(BaseModel): + """ + 当前登录账号一次性关联渠道所需的短时凭据。 + """ + + code: str = Field(description="只返回一次的高熵关联码,不应记录日志或发到群聊") + expires_at: float = Field(description="关联码到期的 UTC Unix 秒") diff --git a/app/schemas/token.py b/app/schemas/token.py index 8c6c1a44a..aa54a0558 100644 --- a/app/schemas/token.py +++ b/app/schemas/token.py @@ -50,3 +50,7 @@ class TokenPayload(BaseModel): default=None, description="宿主 Agent 签发令牌时绑定的渠道发起用户标识;仅宿主内部调用的令牌携带", ) + agent_authorization_id: Optional[str] = Field(default=None, description="统一渠道成员身份;每次请求重新校验当前授权") + agent_operation: Optional[str] = Field(default=None, description="当前受控业务操作,不得复用于其它 API") + agent_method: Optional[str] = Field(default=None, description="本次内部 API 请求的固定 HTTP 方法") + agent_path: Optional[str] = Field(default=None, description="本次内部 API 请求的固定路径,不含查询参数") diff --git a/app/startup/composition/security.py b/app/startup/composition/security.py index 43bfa6efc..e4a7b465c 100644 --- a/app/startup/composition/security.py +++ b/app/startup/composition/security.py @@ -21,6 +21,7 @@ from app.application.security.auth import ( reset_auth_service, validate_token_identity, ) +from app.application.security.authorization import ChannelAuthorizationService, configure_channel_authorization from app.application.security.passkey import ( PASSKEY_CHALLENGE_TTL_SECONDS, PasskeyService, @@ -31,6 +32,7 @@ from app.application.security.passkey import ( ) from app.application.security.user import configure_user_lookups, reset_user_lookups from app.application.security.widget import WidgetScopeFactory +from app.db.adapters.authorization import authorization_scope from app.db.adapters.user import SqlAlchemyUserRepository from app.db.adapters.widget import widget_scope from app.db.oper.passkey import PassKeyOper @@ -91,6 +93,7 @@ def configure_security_services() -> SecurityComposition: 构造并登记认证、用户查询和 PassKey 服务。 """ users = build_transactional_user_repository() + configure_channel_authorization(ChannelAuthorizationService(partial(authorization_scope, SessionFactory))) _backfill_superuser_setting(users) configure_user_lookups( by_id=lambda user_id: build_transactional_user_repository().get_by_id(user_id), @@ -134,6 +137,7 @@ def reset_security_services() -> None: """ 按发布逆序撤销认证、用户查询和 PassKey 服务。 """ + configure_channel_authorization(None) reset_passkey_service() reset_passkey_challenge_cache() reset_auth_service() diff --git a/database/versions/d8a4c6e29170_channel_authorization.py b/database/versions/d8a4c6e29170_channel_authorization.py new file mode 100644 index 000000000..73f4a7444 --- /dev/null +++ b/database/versions/d8a4c6e29170_channel_authorization.py @@ -0,0 +1,197 @@ +""" +将各通知实例的用户与管理员白名单迁移为统一渠道授权。 + +迁移与旧配置清理在同一事务中完成;投递接收人保留但以后不再隐含授予权限。 +""" + +import time +from uuid import NAMESPACE_URL, uuid4, uuid5 + +import sqlalchemy as sa +from alembic import op + +revision = "d8a4c6e29170" +down_revision = "b7c1e3d5f9a2" +branch_labels = None +depends_on = None + +# 冻结升级时的历史渠道键,不依赖未来宿主代码或模块是否已加载。 +_CHANNELS = { + "telegram": ("Telegram", "TELEGRAM_USERS", "TELEGRAM_ADMINS", "TELEGRAM_CHAT_ID", ("telegram_userid",)), + "wechat": ("微信", "", "WECHAT_ADMINS", "WECHAT_BOT_CHAT_ID", ("wechat_userid",)), + "wechatclawbot": ( + "微信ClawBot", + "", + "WECHATCLAWBOT_ADMINS", + "WECHATCLAWBOT_DEFAULT_TARGET", + ("wechatclawbot_userid",), + ), + "feishu": ("飞书", "", "FEISHU_ADMINS", "FEISHU_OPEN_ID", ("feishu_userid", "feishu_openid")), + "qqbot": ("QQ", "", "QQBOT_ADMINS", "QQ_OPENID", ("qq_userid", "qq_openid")), + "discord": ("Discord", "", "DISCORD_ADMINS", "", ("discord_userid",)), + "slack": ("Slack", "", "SLACK_ADMINS", "", ("slack_userid",)), + "vocechat": ("VoceChat", "", "VOCECHAT_ADMINS", "", ("vocechat_userid",)), + "synologychat": ("SynologyChat", "", "SYNOLOGYCHAT_ADMINS", "", ("synologychat_userid",)), +} + + +def _ids(value: object) -> set[str]: + """ + 规整历史逗号分隔的完整平台标识。 + """ + return {item.strip() for item in str(value or "").split(",") if item.strip()} + + +def upgrade() -> None: + """ + 创建统一身份、迁移既有名单和账号绑定,然后原子移除旧名单键。 + """ + bind = op.get_bind() + if "account_type" not in {column["name"] for column in sa.inspect(bind).get_columns("user")}: + op.add_column("user", sa.Column("account_type", sa.String(16), nullable=False, server_default="local")) + if "channelauthorization" not in sa.inspect(bind).get_table_names(): + op.create_table( + "channelauthorization", + sa.Column("id", sa.String(32), primary_key=True), + sa.Column("notification_id", sa.String(128), nullable=False), + sa.Column("channel", sa.String(64), nullable=False), + sa.Column("sender_id", sa.String(256), nullable=False), + sa.Column("display_name", sa.String(256), nullable=False), + sa.Column("status", sa.String(16), nullable=False), + sa.Column("role", sa.String(16), nullable=False), + sa.Column("scopes", sa.JSON(), nullable=False), + sa.Column("user_id", sa.Integer(), nullable=False), + sa.Column("user_identity", sa.String(32), nullable=False), + sa.Column("linked_user_id", sa.Integer()), + sa.Column("aliases", sa.JSON(), nullable=False), + sa.Column("created_at", sa.Float(), nullable=False), + sa.Column("updated_at", sa.Float(), nullable=False), + sa.Column("origin", sa.String(16), nullable=False), + sa.Column("reviewed_by", sa.Integer()), + ) + op.create_index( + "ux_channel_authorization_sender", "channelauthorization", ["notification_id", "sender_id"], unique=True + ) + for name in ("agenttask", "agenttaskrun"): + if "execution_authorization_id" not in {column["name"] for column in sa.inspect(bind).get_columns(name)}: + op.add_column(name, sa.Column("execution_authorization_id", sa.String(32))) + if "channelbinding" not in sa.inspect(bind).get_table_names(): + op.create_table( + "channelbinding", + sa.Column("id", sa.String(64), primary_key=True), + sa.Column("user_id", sa.Integer(), nullable=False), + sa.Column("user_identity", sa.String(32), nullable=False), + sa.Column("expires_at", sa.Float(), nullable=False), + ) + metadata = sa.MetaData() + users = sa.Table("user", metadata, autoload_with=bind) + members = sa.Table("channelauthorization", metadata, autoload_with=bind) + system = sa.Table("systemconfig", metadata, autoload_with=bind) + row = bind.execute(sa.select(system).where(system.c.key == "Notifications")).mappings().first() + if row is None or not isinstance(row["value"], list): + return + configs = [] + accounts = list(bind.execute(sa.select(users).where(users.c.account_type == "local")).mappings()) + now = time.time() + for raw in row["value"]: + if not isinstance(raw, dict): + configs.append(raw) + continue + config = dict(raw) + config["id"] = str(config.get("id") or uuid4()) + definition = _CHANNELS.get(config.get("type")) + if definition is None: + configs.append(config) + continue + channel, users_key, admins_key, primary_key, bindings = definition + values = dict(config.get("config") or {}) + roles = dict.fromkeys(_ids(values.get(users_key)), "member") + admins = _ids(values.get(admins_key)) + if primary_key and (config["type"] != "wechat" or values.get("WECHAT_MODE", "app") == "bot"): + admins.update(_ids(values.get(primary_key))) + for account in accounts: + for key in bindings: + bound = str((account["settings"] or {}).get(key) or "").strip() + if bound and (not values.get(users_key) or bound in roles or bound in admins): + roles.setdefault(bound, "member") + roles.update(dict.fromkeys(admins, "admin")) + for sender_id, role in sorted(roles.items()): + existing = bind.execute( + sa.select(members.c.id).where( + members.c.notification_id == config["id"], members.c.sender_id == sender_id + ) + ).first() + if existing is not None: + continue + identity = uuid5(NAMESPACE_URL, f"moviepilot:channel:{config['id']}:{sender_id}").hex + linked = [ + account + for account in accounts + if any(str((account["settings"] or {}).get(key) or "") == sender_id for key in bindings) + ] + if len(linked) == 1: + user_id = linked[0]["id"] + user_identity = linked[0]["notification_identity"] + else: + user_identity = uuid4().hex + result = bind.execute( + users.insert().values( + name=f"channel_{identity}", + account_type="channel", + is_active=True, + is_superuser=False, + notification_identity=user_identity, + hashed_password=None, + permissions={}, + settings={bindings[0]: sender_id}, + is_otp=False, + ) + ) + user_id = result.inserted_primary_key[0] + bind.execute( + members.insert().values( + id=identity, + notification_id=config["id"], + channel=channel, + sender_id=sender_id, + display_name=linked[0]["name"] if len(linked) == 1 else sender_id, + status="pending" if len(linked) > 1 else "approved", + role=role, + scopes=["search", "subscribe", "download", "schedule"], + user_id=user_id, + user_identity=user_identity, + linked_user_id=user_id if len(linked) == 1 and role != "admin" else None, + aliases=[], + created_at=now, + updated_at=now, + origin="legacy", + ) + ) + tasks = sa.Table("agenttask", sa.MetaData(), autoload_with=bind) + if {"channel", "source", "user_id", "execution_user_id", "execution_user_identity"}.issubset( + tasks.c.keys() + ): + bind.execute( + tasks.update() + .where( + tasks.c.channel == channel, + tasks.c.source == config.get("name"), + tasks.c.user_id == sender_id, + tasks.c.execution_user_id == user_id, + tasks.c.execution_user_identity == user_identity, + tasks.c.execution_authorization_id.is_(None), + ) + .values(user_id=f"channel:{identity}", execution_authorization_id=identity) + ) + values.pop(users_key, None) + values.pop(admins_key, None) + config["config"] = values + configs.append(config) + bind.execute(system.update().where(system.c.id == row["id"]).values(value=configs)) + + +def downgrade() -> None: + """ + 拒绝丢失已迁移授权及业务归属的自动降级,回退应恢复升级前完整数据库备份。 + """ + raise RuntimeError("渠道授权迁移包含持久化身份与权限,请使用升级前数据库备份回退") diff --git a/docs/agent-execution.md b/docs/agent-execution.md index 76f3b8800..ac2e7c566 100644 --- a/docs/agent-execution.md +++ b/docs/agent-execution.md @@ -30,17 +30,17 @@ ## 自主任务执行账号 -`agent_task create` 在创建时解析真实 MoviePilot 账号。Telegram 等渠道必须绑定唯一且已启用的 -MoviePilot 用户;请在右上角头像 → 个人信息 → 账号绑定中填写渠道发送者完整 ID,不能填写昵称、 -群 ID 或机器人 ID。Web 使用已登录的用户 ID,已认证的 API 集成使用宿主管理员账号。 +`agent_task create` 在创建时固定执行账号。通知渠道使用公共授权中已批准的成员身份,并要求 +定时任务能力;无需创建网页登录账号。管理员在用户管理右下角“渠道授权”弹窗管理成员。 +Web 使用已登录的用户 ID,已认证的 API 集成使用宿主管理员账号。申请、迁移和账号关联见 +[通知渠道授权](channel-authorization.md)。 -任务分别保存渠道会话归属和执行账号。后台执行仍按该账号的通知设置回传结果,普通业务查询和 +任务分别保存渠道会话归属、固定授权身份和执行账号。渠道任务通过原通知实例的当前名称私聊回传,普通业务查询和 管理员操作使用同一账号的实时权限,不因后台运行而提升权限。改名不会改变执行主体;账号停用、 删除或被新账号替换时,本次执行记录为 `failed`,不调用模型,也不回退超级管理员。 -升级前的任务保留原定义和运行历史,但不猜测其执行主体。请先确认账号绑定,再从创建任务的 -原会话使用 `agent_task update` 更新任务(例如保持名称不变),以确认一次执行账号;也可删除后 -重新创建。未确认的任务执行时会明确失败,仍可暂停或删除。已确认主体不能通过普通更新换成另一账号。 +升级前的任务保留原定义和运行历史,只有原渠道、发送者与已确认执行账号一致时自动接入对应授权。 +无法确认的旧渠道任务需从原会话删除后重新创建,不猜测执行主体。已确认主体不能通过普通更新换成另一账号。 `last_status=success` 表示 Agent 本轮未遇到宿主识别的执行、身份或权限错误,不保证每项外部业务 已完成;入库重试等异步操作仍应查询对应业务记录核验结果。 diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md index d66ffc031..ff7ff8d32 100644 --- a/docs/architecture-overview.md +++ b/docs/architecture-overview.md @@ -845,13 +845,13 @@ flowchart LR ### 10.2 当前架构快照 -以下是 2026-11-14 核对的 `tests/fixtures/architecture/` 数据;这是源码合同快照, +以下是 2026-11-17 核对的 `tests/fixtures/architecture/` 数据;这是源码合同快照, 不代表某个已发布镜像或正在运行的实例已经验证。 | 指标 | 当前值 | |---|---:| -| Python 模块 | 1168 | -| 内部导入边 | 10,230 | +| Python 模块 | 1178 | +| 内部导入边 | 10,327 | | 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) | | Application / Chain 具体 Adapter 直连 | 0 / 0 | | Direct egress | 51(精确 policy 准入,Application / Chain 均为 0) | diff --git a/docs/channel-authorization.md b/docs/channel-authorization.md new file mode 100644 index 000000000..c1cc35364 --- /dev/null +++ b/docs/channel-authorization.md @@ -0,0 +1,33 @@ +# 通知渠道授权 + +在用户管理右下角点击“渠道授权”,可以统一处理申请、设置成员能力、停用或恢复成员。原来分散在各通知渠道配置中的用户和管理员白名单不再单独维护。渠道授权仅由 MoviePilot 网页系统管理员管理,渠道管理员不能继续给别人授权。 + +## 使用流程 + +用户在机器人中发送“申请使用”,或点击需要授权时显示的申请按钮。系统管理员在渠道授权弹窗批准后,机器人会向成员发送回执。批准不会自动重放之前的订阅或下载请求,用户需要重新发送要执行的操作。 + +普通成员通过受控 Agent 搜索、订阅和下载;定时任务另行开启。传统管理命令和旧式业务按钮仅渠道管理员可用,普通文本不再进入旧管理会话。管理员角色允许实例管理操作,设置时应单独核对。成员身份按通知实例和平台用户 ID 隔离,同一个人在不同机器人中分别授权。昵称、群组 ID 和机器人 ID 不能代替用户身份。 + +只使用机器人无需创建网页登录账号。系统为订阅、下载和任务保存内部归属,该身份不会出现在网页登录用户列表,也没有密码、PassKey 或网页登录能力。停用成员后,后续 API、工具、子代理和定时任务都重新校验授权;已经发出的外部业务请求不会因为停用而自动撤销。 + +## 关联已有账号 + +登录 MoviePilot 后,在个人信息的账号绑定区域生成一次性关联码。五分钟内在机器人私聊中发送 `绑定账号 关联码`;不要在群里发送。关联码只保存摘要,使用一次后失效,生成新码会撤销旧码。 + +关联验证账号和渠道两方身份,并迁移该成员自己的订阅与下载归属;执行中的任务或归属冲突会拒绝合并,保持原数据。关联不替代渠道审批,也不会解除停用。关联后的有效权限同时受网页账号与渠道授权限制;重新绑定不能绕过网页账号停用。 + +## 升级迁移 + +升级迁移逐实例导入 Telegram 普通用户名单,以及 Telegram、企业微信、微信 ClawBot、飞书、QQ、Discord、Slack、VoceChat、SynologyChat 的管理员名单。原默认主用户具有管理员语义的渠道会保留这项已有授权;投递接收人、群组和默认目标配置继续保留,但升级后修改这些投递字段不会自动授予权限。 + +已有唯一网页账号绑定保留其业务归属。重复绑定不会猜测执行账号,记录保留为待确认状态。旧任务仅在渠道、发送者和已确认执行账号都吻合时接入对应授权;无法确认的旧任务需从原会话重新创建。 + +旧名单清理与授权导入在同一数据库迁移事务中完成。重复升级不覆盖新授权的停用或权限调整。迁移涉及持久化业务身份,回退应恢复升级前完整数据库备份,不直接降级丢弃新表。 + +## 开发边界 + +`app/application/security/authorization.py` 拥有申请、审批和实时权限投影;`app/db/oper/authorization.py` 使用调用方 Session 暂存查询与变更;`app/db/adapters/authorization.py` 管理短事务。模型只保存数据,渠道适配器只提供平台证明的发送者身份。 + +内部 Agent API 令牌签名绑定授权 ID、operation、HTTP 方法和路径。每次请求重新读取当前角色与能力,不下发网页登录资源 Cookie,也不能转用于其它 API。普通成员的下载查询在分页前按归属收窄,定时任务固定授权身份与账号不可变身份。 + +异步 API 用户依赖和下载历史读取通过已等待的受控线程入口读取同步授权端口;每次操作在 worker 内创建并关闭独占 Session,不在事件循环执行同步 SQL,不遗留后台任务。Agent 使用现有 `db` 能力桶,取消后不提前释放底层阻塞调用名额。新增授权端点、Schema、应用服务、领域合同和 ORM 注册带来必要的冷导入模块增加;冷导入时间预算保持 3000ms。 diff --git a/docs/mcp-api.md b/docs/mcp-api.md index 6ead0fd09..d8d8b5f4d 100644 --- a/docs/mcp-api.md +++ b/docs/mcp-api.md @@ -274,6 +274,14 @@ Web 影视精确与标题 SSE 的 `manual_paging=true` 模式在最终 `done` ### 通知配置与交互身份 +渠道用户和管理员统一在用户管理右下角“渠道授权”弹窗管理。`GET /api/v1/authorization/` +返回成员和脱敏渠道目录;`POST /api/v1/authorization/` 直接添加授权, +`PUT /api/v1/authorization/{member_id}` 批准、拒绝、调整或停用。仅网页登录系统管理员可管理。 +`POST /api/v1/authorization/binding` 为当前已登录账号生成五分钟一次性关联码,由本人在原渠道私聊提交。 +成员无需网页登录账号,普通成员 API 只开放明确的搜索、订阅、下载能力,定时任务另行授权。 +渠道内部令牌限定 operation、HTTP 方法与路径,并实时校验授权,不可用于其它路由或网页登录。 +旧白名单按通知实例迁移,投递接收人不再隐含授权。详见[通知渠道授权](channel-authorization.md)。 + `slash.run` 返回的是命令已触发,不代表后台命令或通知已完成。消息渠道发起的命令使用 宿主签名的渠道用户身份;请求头不能指定其他用户,渠道身份缺失或不匹配时会拒绝执行。 Web 会话沿用当前用户;无渠道调用不携带收件人,插件回执按既有管理员通知目标路由, diff --git a/scripts/generate_agent_skill_docs.py b/scripts/generate_agent_skill_docs.py index d8213d0a6..9a35c3e9b 100644 --- a/scripts/generate_agent_skill_docs.py +++ b/scripts/generate_agent_skill_docs.py @@ -18,11 +18,21 @@ if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) # 与对应 SKILL.md 同步维护,重新生成不能回退用户同步所需的版本。 -MOVIEPILOT_API_SKILL_VERSION = "76" -DATABASE_OPERATION_SKILL_VERSION = "19" +MOVIEPILOT_API_SKILL_VERSION = "77" +DATABASE_OPERATION_SKILL_VERSION = "20" DATABASE_TABLE_GUIDES: dict[str, tuple[str, str, str]] = { + "channelauthorization": ( + "Stores per-instance channel authorization, approval state, scopes, and immutable business ownership.", + "Inspecting requests, member capabilities, suspension, and legacy whitelist migration.", + "Owned by channel authorization; never bypass approval, account linking, or live revocation with direct writes.", + ), + "channelbinding": ( + "Stores web-initiated one-time channel binding digests and their five-minute expiry.", + "Checking expiry or consumption without reading or reconstructing the original binding code.", + "Consumed atomically by two-sided identity verification; never extend expiry, forge digests, or replace owners directly.", + ), "alembic_version": ( "Records the Alembic migration revision currently applied to the database.", "Diagnosing startup migration failures or a database/code revision mismatch.", diff --git a/skills/database-operation/SKILL.md b/skills/database-operation/SKILL.md index dd9c1fea0..e42e789b6 100644 --- a/skills/database-operation/SKILL.md +++ b/skills/database-operation/SKILL.md @@ -1,6 +1,6 @@ --- name: database-operation -version: 19 +version: 20 description: >- Use this skill when you need to inspect, query, maintain, or carefully modify the MoviePilot database. This skill uses the bundled scripts/mp-db.py helper, @@ -178,13 +178,13 @@ and pass the flag only for an explicitly authorized repair. - Purpose: Stores one-shot or recurring Agent task definitions, triggers, and the latest execution summary. - Useful queries: Inspecting task ownership, enablement, cron/run_at settings, and the latest result. - Write boundary: Create, update, enable, disable, or delete tasks through the Agent task API. -- Columns: `id`, `name`, `content`, `trigger_type`, `cron_expression`, `run_at`, `enabled`, `user_id`, `username`, `execution_user_id`, `execution_user_identity`, `session_id`, `channel`, `source`, `original_chat_id`, `last_status`, `last_run_at`, `last_result`, `last_run_id`, `run_count`, `created_at`, `updated_at` +- Columns: `id`, `name`, `content`, `trigger_type`, `cron_expression`, `run_at`, `enabled`, `user_id`, `username`, `execution_user_id`, `execution_user_identity`, `execution_authorization_id`, `session_id`, `channel`, `source`, `original_chat_id`, `last_status`, `last_run_at`, `last_result`, `last_run_id`, `run_count`, `created_at`, `updated_at` ### `agenttaskrun` - Purpose: Stores the input snapshot, status, timestamps, and result of each Agent task execution. - Useful queries: Auditing one run or correlating a failure with task_id, run_id, and trigger source. - Write boundary: Execution evidence owned by the task runner; never fabricate rows or edit run status. -- Columns: `id`, `run_id`, `task_id`, `trigger_source`, `name`, `content`, `trigger_type`, `cron_expression`, `run_at`, `user_id`, `username`, `execution_user_id`, `execution_user_identity`, `session_id`, `channel`, `message_source`, `original_chat_id`, `status`, `started_at`, `finished_at`, `result` +- Columns: `id`, `run_id`, `task_id`, `trigger_source`, `name`, `content`, `trigger_type`, `cron_expression`, `run_at`, `user_id`, `username`, `execution_user_id`, `execution_user_identity`, `execution_authorization_id`, `session_id`, `channel`, `message_source`, `original_chat_id`, `status`, `started_at`, `finished_at`, `result` ### `alembic_version` - Purpose: Records the Alembic migration revision currently applied to the database. @@ -192,6 +192,18 @@ and pass the flag only for an explicitly authorized repair. - Write boundary: Never edit it directly; advance or roll back revisions only through Alembic. - Columns: `version_num` +### `channelauthorization` +- Purpose: Stores per-instance channel authorization, approval state, scopes, and immutable business ownership. +- Useful queries: Inspecting requests, member capabilities, suspension, and legacy whitelist migration. +- Write boundary: Owned by channel authorization; never bypass approval, account linking, or live revocation with direct writes. +- Columns: `id`, `notification_id`, `channel`, `sender_id`, `display_name`, `status`, `role`, `scopes`, `user_id`, `user_identity`, `linked_user_id`, `aliases`, `created_at`, `updated_at`, `origin`, `reviewed_by` + +### `channelbinding` +- Purpose: Stores web-initiated one-time channel binding digests and their five-minute expiry. +- Useful queries: Checking expiry or consumption without reading or reconstructing the original binding code. +- Write boundary: Consumed atomically by two-sided identity verification; never extend expiry, forge digests, or replace owners directly. +- Columns: `id`, `user_id`, `user_identity`, `expires_at` + ### `downloadfailure` - Purpose: Stores stable fingerprints, media/torrent context, errors, and retry scheduling for failed downloads. - Useful queries: Analyzing failure causes, retry counts, next retry time, and affected media or sites. @@ -359,7 +371,7 @@ and pass the flag only for an explicitly authorized repair. - Purpose: Stores user accounts, password hashes, administrator state, OTP, permissions, and preferences. - Useful queries: Authorized diagnostics of account state, permissions, or authentication configuration. - Write boundary: Security-sensitive; manage through user, permission, password, and two-factor APIs. -- Columns: `id`, `name`, `email`, `hashed_password`, `is_active`, `is_superuser`, `avatar`, `is_otp`, `otp_secret`, `permissions`, `settings`, `notification_identity` +- Columns: `id`, `name`, `account_type`, `email`, `hashed_password`, `is_active`, `is_superuser`, `avatar`, `is_otp`, `otp_secret`, `permissions`, `settings`, `notification_identity` ### `userconfig` - Purpose: Stores per-user JSON configuration isolated by username and key. diff --git a/skills/moviepilot-api/SKILL.md b/skills/moviepilot-api/SKILL.md index a5c3fdfbd..47a8fcfed 100644 --- a/skills/moviepilot-api/SKILL.md +++ b/skills/moviepilot-api/SKILL.md @@ -1,6 +1,6 @@ --- name: moviepilot-api -version: 76 +version: 77 description: >- Use this skill for MoviePilot product operations such as media search, torrent search, downloads, subscriptions, library checks, sites, storage, workflows, @@ -111,11 +111,11 @@ Passkey origins and is not the gateway base URL. Keep it configured even when the public reverse proxy is unreachable from inside the container. `subscription.add`, `subscription.update`, and `subscription.delete` require -authorization for the action and scope and use the active MoviePilot user bound to the channel account, +authorization for the action and scope and use the channel member identity verified by the host, including for channel administrators. Creation belongs to that user; ordinary -users may update or delete only their own subscriptions. An unbound or inactive -channel user must bind an active account before retrying, not switch to an -administrator identity. +users may update or delete only their own subscriptions. A channel member needs +current approval from a MoviePilot administrator; account binding is optional +and must not substitute an administrator identity. `subscription.list` uses the current user identity and subscription ownership filtering. The separate global subscription integration endpoint requires a valid API_TOKEN @@ -276,9 +276,9 @@ does not trigger `has_update`. Use `plugin.source.options` to inspect alternativ sources; switching sources still requires an explicit source change. Installed plugins without a bound source retain market candidates for source selection. -Operations declare an identity scope: `public` reads external public metadata without requiring a channel account binding; `bound_user` uses the active MoviePilot user bound to the stable channel sender ID (Web uses its authenticated user ID); `admin` requires administrator authority. Read-only does not mean public. Channel nicknames never establish identity. Personal records and subscription writes retain their existing ownership and permission checks. +Operations declare an identity scope: `public` reads external public metadata without account binding or approval; `bound_user` uses the host-verified channel authorization (Web uses its authenticated user ID); `admin` requires current administrator authority. Channel members do not need web-login accounts. Read-only does not mean public. Nicknames never establish identity. Personal subscriptions and downloads retain owner checks. See `docs/channel-authorization.md` for approval, migration, and account linking. -When identity resolution fails, relay the gateway's actual remediation message and sender ID. Channel users bind their own MoviePilot account via avatar > Personal Information > Account Binding, fill the named channel field, and save. Do not invent a Settings > Users binding page, substitute nicknames/group/bot IDs, diagnose an ambiguous binding failure as a network issue, or ask Web users to bind a notification channel. Public operations do not require binding. +When identity resolution fails, relay the actual gateway remediation. Channel users send `/apply` and a MoviePilot web administrator approves through the authorization dialog opened from User Management. Existing web accounts may generate a one-time binding code in their profile and complete linking in their own bot private chat. Never substitute nicknames, group IDs, bot IDs, or an administrator account; do not diagnose authorization failure as a network error. Web users need no channel binding. Public operations remain available without approval. This Skill is the complete callable MoviePilot business API surface for the Agent. Every operation in `allowed-api-operations` has one exact parameter @@ -405,7 +405,7 @@ token exchange downloads retain their existing credential rules. ## Agent Task And Conversation State - For `agent_task` updates, `enabled=null` preserves the current enabled state. Renaming a paused task does not resume its schedule. -- `agent_task` pins a real execution account at creation. Channel senders must uniquely bind to an active MoviePilot user. Background API calls retain that account's permissions, and invalid identity fails the run. Confirm legacy tasks with `update` in their original conversation or recreate them; never substitute a same-name account or fall back to the superuser. +- `agent_task` pins both the execution account and channel authorization at creation. Channel members need the schedule capability, not a web-login account. Background APIs, tools, and subagents recheck that same identity and live authority. Recreate unconfirmed legacy channel tasks in the original conversation; never substitute a same-name account or fall back to the superuser. - Traditional message sessions are scoped by channel, configured source, and user ID. A stop, clear, status query, or confirmation targets the current source's session. - Background WebAgent completion appends the current turn to display history. Frontend complete snapshots keep their existing replacement contract. - Complete snapshot replacement retains hidden choice receipts so delayed snapshots cannot restore a selected card to pending; ordinary messages retain replacement behavior. diff --git a/tests/conftest.py b/tests/conftest.py index 2e2288bd1..8dc6ac3d9 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -138,6 +138,23 @@ def compose_cache_backend(): configure_cache_composition() +@pytest.fixture(autouse=True) +def isolate_channel_authorization_service(): + """ + 隔离启动测试登记的渠道授权服务,显式授权用例自行装配临时数据库服务。 + + :yields: 没有隐式渠道配置的测试阶段;退出时恢复原进程提供方 + """ + from app.application.security.authorization import configure_channel_authorization, get_channel_authorization + + previous = get_channel_authorization() + configure_channel_authorization(None) + try: + yield + finally: + configure_channel_authorization(previous) + + @pytest.fixture(autouse=True) def install_runtime_settings_test_proxies(monkeypatch): """ diff --git a/tests/fixtures/architecture/concurrency-baseline.json b/tests/fixtures/architecture/concurrency-baseline.json index 9c44b0139..7dea4b962 100644 --- a/tests/fixtures/architecture/concurrency-baseline.json +++ b/tests/fixtures/architecture/concurrency-baseline.json @@ -228,6 +228,12 @@ }, "target": "asyncio.create_task" }, + "app/api/dependencies/auth.py:app.runtime.execution.run_in_threadpool": { + "owners": { + "get_current_user_async": 1 + }, + "target": "app.runtime.execution.run_in_threadpool" + }, "app/api/endpoints/anthropic.py:app.runtime.execution.run_in_threadpool": { "owners": { "_check_auth": 1 @@ -241,11 +247,17 @@ }, "target": "app.runtime.execution.run_in_threadpool" }, + "app/api/endpoints/history.py:app.runtime.execution.run_in_threadpool": { + "owners": { + "download_history": 1 + }, + "target": "app.runtime.execution.run_in_threadpool" + }, "app/api/endpoints/history.py:asyncio.to_thread": { "owners": { + "_grant_manual_identity_authorization": 1, "ai_redo_transfer_history": 1, - "batch_ai_redo_transfer_history": 1, - "_grant_manual_identity_authorization": 1 + "batch_ai_redo_transfer_history": 1 }, "target": "asyncio.to_thread" }, diff --git a/tests/fixtures/architecture/dependency-baseline.json b/tests/fixtures/architecture/dependency-baseline.json index f282fdb14..346cb6469 100644 --- a/tests/fixtures/architecture/dependency-baseline.json +++ b/tests/fixtures/architecture/dependency-baseline.json @@ -977,8 +977,8 @@ "runtime_only": true } }, - "edge_count": 10230, - "edge_sha256": "8493fad27c51627bec333bc13383600490d123e01c3d7977dd8a710e3356688b", + "edge_count": 10327, + "edge_sha256": "589cb701a3165274376cf992cb7cbdc77f44f22e041d5ff424472b43adf9c17b", "edges": [ "app -> app.foundation", "app -> app.foundation.environment", @@ -1263,8 +1263,11 @@ "app.agent.api.executor -> app.agent.policy.api", "app.agent.api.executor -> app.agent.policy.contracts", "app.agent.api.executor -> app.agent.policy.sanitizer", + "app.agent.api.executor -> app.agent.tools", + "app.agent.api.executor -> app.agent.tools.base", "app.agent.api.executor -> app.application", "app.agent.api.executor -> app.application.security", + "app.agent.api.executor -> app.application.security.authorization", "app.agent.api.executor -> app.application.security.token", "app.agent.api.executor -> app.runtime", "app.agent.api.executor -> app.runtime.log", @@ -1385,6 +1388,7 @@ "app.agent.identity -> app.application", "app.agent.identity -> app.application.security", "app.agent.identity -> app.application.security.auth", + "app.agent.identity -> app.application.security.authorization", "app.agent.identity -> app.application.security.user", "app.agent.identity -> app.schemas", "app.agent.identity -> app.schemas.types", @@ -1648,12 +1652,16 @@ "app.agent.middleware.policy -> app.agent.policy.registry", "app.agent.middleware.policy -> app.agent.policy.sanitizer", "app.agent.middleware.policy -> app.agent.tools", + "app.agent.middleware.policy -> app.agent.tools.base", "app.agent.middleware.policy -> app.agent.tools.catalog", "app.agent.middleware.policy -> app.agent.tools.impl", "app.agent.middleware.policy -> app.agent.tools.impl.api", "app.agent.middleware.policy -> app.agent.tools.impl.mcp", "app.agent.middleware.policy -> app.agent.tools.result", "app.agent.middleware.policy -> app.agent.tools.tags", + "app.agent.middleware.policy -> app.application", + "app.agent.middleware.policy -> app.application.security", + "app.agent.middleware.policy -> app.application.security.authorization", "app.agent.middleware.recall -> app.agent", "app.agent.middleware.recall -> app.agent.history", "app.agent.middleware.recall -> app.agent.history.message", @@ -1770,6 +1778,7 @@ "app.agent.orchestrator -> app.agent.terminal", "app.agent.orchestrator -> app.agent.terminal.ownership", "app.agent.orchestrator -> app.agent.tools", + "app.agent.orchestrator -> app.agent.tools.base", "app.agent.orchestrator -> app.agent.tools.catalog", "app.agent.orchestrator -> app.agent.tools.impl", "app.agent.orchestrator -> app.agent.tools.impl.api", @@ -1782,6 +1791,8 @@ "app.agent.orchestrator -> app.application.messaging.recall", "app.agent.orchestrator -> app.application.plugin", "app.agent.orchestrator -> app.application.plugin.runtime", + "app.agent.orchestrator -> app.application.security", + "app.agent.orchestrator -> app.application.security.authorization", "app.agent.orchestrator -> app.chain", "app.agent.orchestrator -> app.chain.agent", "app.agent.orchestrator -> app.foundation", @@ -1882,10 +1893,16 @@ "app.agent.tasks -> app.agent.orchestrator", "app.agent.tasks -> app.agent.prompt", "app.agent.tasks -> app.agent.runtime", + "app.agent.tasks -> app.agent.tools", + "app.agent.tasks -> app.agent.tools.base", "app.agent.tasks -> app.application", "app.agent.tasks -> app.application.agenttask", + "app.agent.tasks -> app.application.security", + "app.agent.tasks -> app.application.security.authorization", "app.agent.tasks -> app.chain", "app.agent.tasks -> app.chain.agent", + "app.agent.tasks -> app.domain", + "app.agent.tasks -> app.domain.authorization", "app.agent.tasks -> app.foundation", "app.agent.tasks -> app.foundation.identity", "app.agent.tasks -> app.runtime", @@ -1926,6 +1943,8 @@ "app.agent.tools.base -> app.application.messaging.channel", "app.agent.tools.base -> app.application.messaging.channel.admin", "app.agent.tools.base -> app.application.notification", + "app.agent.tools.base -> app.application.security", + "app.agent.tools.base -> app.application.security.authorization", "app.agent.tools.base -> app.chain", "app.agent.tools.base -> app.chain.base", "app.agent.tools.base -> app.foundation", @@ -1984,6 +2003,7 @@ "app.agent.tools.impl.agent_task -> app.application.agenttask", "app.agent.tools.impl.agent_task -> app.application.scheduling", "app.agent.tools.impl.agent_task -> app.application.security", + "app.agent.tools.impl.agent_task -> app.application.security.authorization", "app.agent.tools.impl.agent_task -> app.application.security.user", "app.agent.tools.impl.agent_task -> app.runtime", "app.agent.tools.impl.agent_task -> app.runtime.scheduling", @@ -2004,6 +2024,7 @@ "app.agent.tools.impl.api -> app.application", "app.agent.tools.impl.api -> app.application.security", "app.agent.tools.impl.api -> app.application.security.auth", + "app.agent.tools.impl.api -> app.application.security.authorization", "app.agent.tools.impl.api -> app.schemas", "app.agent.tools.impl.api -> app.schemas.common", "app.agent.tools.impl.api -> app.schemas.types", @@ -2248,9 +2269,12 @@ "app.api.dependencies.auth -> app.application", "app.api.dependencies.auth -> app.application.security", "app.api.dependencies.auth -> app.application.security.auth", + "app.api.dependencies.auth -> app.application.security.authorization", "app.api.dependencies.auth -> app.application.security.passkey", "app.api.dependencies.auth -> app.application.security.user", "app.api.dependencies.auth -> app.application.security.userconfig", + "app.api.dependencies.auth -> app.runtime", + "app.api.dependencies.auth -> app.runtime.execution", "app.api.dependencies.auth -> app.schemas", "app.api.dependencies.auth -> app.schemas.token", "app.api.dependencies.auth -> app.startup", @@ -2478,6 +2502,23 @@ "app.api.endpoints.auth -> app.schemas", "app.api.endpoints.auth -> app.schemas.token", "app.api.endpoints.auth -> app.schemas.user", + "app.api.endpoints.authorization -> app.api", + "app.api.endpoints.authorization -> app.api.dependencies", + "app.api.endpoints.authorization -> app.api.dependencies.auth", + "app.api.endpoints.authorization -> app.api.response", + "app.api.endpoints.authorization -> app.application", + "app.api.endpoints.authorization -> app.application.notification", + "app.api.endpoints.authorization -> app.application.security", + "app.api.endpoints.authorization -> app.application.security.authorization", + "app.api.endpoints.authorization -> app.chain", + "app.api.endpoints.authorization -> app.chain.message", + "app.api.endpoints.authorization -> app.domain", + "app.api.endpoints.authorization -> app.domain.authorization", + "app.api.endpoints.authorization -> app.schemas", + "app.api.endpoints.authorization -> app.schemas.authorization", + "app.api.endpoints.authorization -> app.schemas.message", + "app.api.endpoints.authorization -> app.schemas.response", + "app.api.endpoints.authorization -> app.schemas.types", "app.api.endpoints.bangumi -> app.adapters", "app.api.endpoints.bangumi -> app.adapters.web", "app.api.endpoints.bangumi -> app.adapters.web.security", @@ -2644,10 +2685,13 @@ "app.api.endpoints.history -> app.application.configuration", "app.api.endpoints.history -> app.application.history", "app.api.endpoints.history -> app.application.history.registration", + "app.api.endpoints.history -> app.application.security", + "app.api.endpoints.history -> app.application.security.authorization", "app.api.endpoints.history -> app.application.transfer", "app.api.endpoints.history -> app.application.transfer.execution", "app.api.endpoints.history -> app.application.transfer.recovery", "app.api.endpoints.history -> app.runtime", + "app.api.endpoints.history -> app.runtime.execution", "app.api.endpoints.history -> app.runtime.log", "app.api.endpoints.history -> app.runtime.loop", "app.api.endpoints.history -> app.runtime.progress", @@ -2908,6 +2952,8 @@ "app.api.endpoints.notification -> app.application.configuration", "app.api.endpoints.notification -> app.chain", "app.api.endpoints.notification -> app.chain.notification", + "app.api.endpoints.notification -> app.domain", + "app.api.endpoints.notification -> app.domain.authorization", "app.api.endpoints.notification -> app.schemas", "app.api.endpoints.notification -> app.schemas.common", "app.api.endpoints.notification -> app.schemas.push", @@ -3480,6 +3526,7 @@ "app.api.routers -> app.api.endpoints.anilist", "app.api.routers -> app.api.endpoints.anthropic", "app.api.routers -> app.api.endpoints.auth", + "app.api.routers -> app.api.endpoints.authorization", "app.api.routers -> app.api.endpoints.bangumi", "app.api.routers -> app.api.endpoints.classification", "app.api.routers -> app.api.endpoints.dashboard", @@ -3897,6 +3944,10 @@ "app.application.messaging.agent -> app.schemas", "app.application.messaging.agent -> app.schemas.message", "app.application.messaging.agent -> app.schemas.types", + "app.application.messaging.channel.admin -> app.application", + "app.application.messaging.channel.admin -> app.application.notification", + "app.application.messaging.channel.admin -> app.application.security", + "app.application.messaging.channel.admin -> app.application.security.authorization", "app.application.messaging.channel.admin -> app.schemas", "app.application.messaging.channel.admin -> app.schemas.types", "app.application.messaging.chat -> app.application", @@ -4228,6 +4279,7 @@ "app.application.security.auth -> app.application", "app.application.security.auth -> app.application.configuration", "app.application.security.auth -> app.application.security", + "app.application.security.auth -> app.application.security.authorization", "app.application.security.auth -> app.application.security.token", "app.application.security.auth -> app.application.security.user", "app.application.security.auth -> app.application.site", @@ -4236,6 +4288,14 @@ "app.application.security.auth -> app.schemas", "app.application.security.auth -> app.schemas.token", "app.application.security.auth -> app.schemas.user", + "app.application.security.authorization -> app.application", + "app.application.security.authorization -> app.application.notification", + "app.application.security.authorization -> app.application.security", + "app.application.security.authorization -> app.application.security.user", + "app.application.security.authorization -> app.domain", + "app.application.security.authorization -> app.domain.authorization", + "app.application.security.authorization -> app.schemas", + "app.application.security.authorization -> app.schemas.system", "app.application.security.cookie -> app.application", "app.application.security.cookie -> app.application.security", "app.application.security.cookie -> app.application.security.twofactor", @@ -5262,6 +5322,8 @@ "app.chain.message -> app.application.messaging.skill", "app.chain.message -> app.application.messaging.subscribe", "app.chain.message -> app.application.messaging.update", + "app.chain.message -> app.application.security", + "app.chain.message -> app.application.security.authorization", "app.chain.message -> app.chain", "app.chain.message -> app.chain.base", "app.chain.message -> app.chain.interaction", @@ -6528,6 +6590,17 @@ "app.db.adapters.agent -> app.db.uow", "app.db.adapters.agent -> app.schemas", "app.db.adapters.agent -> app.schemas.common", + "app.db.adapters.authorization -> app.application", + "app.db.adapters.authorization -> app.application.security", + "app.db.adapters.authorization -> app.application.security.authorization", + "app.db.adapters.authorization -> app.application.security.user", + "app.db.adapters.authorization -> app.db", + "app.db.adapters.authorization -> app.db.adapters", + "app.db.adapters.authorization -> app.db.adapters.user", + "app.db.adapters.authorization -> app.db.models", + "app.db.adapters.authorization -> app.db.models.authorization", + "app.db.adapters.authorization -> app.db.oper", + "app.db.adapters.authorization -> app.db.oper.authorization", "app.db.adapters.chain -> app.application", "app.db.adapters.chain -> app.application.chain", "app.db.adapters.chain -> app.application.chain.events", @@ -6860,6 +6933,8 @@ "app.db.models.agenttaskrun -> app.db.base", "app.db.models.agenttaskrun -> app.db.models", "app.db.models.agenttaskrun -> app.db.models.agenttask", + "app.db.models.authorization -> app.db", + "app.db.models.authorization -> app.db.base", "app.db.models.downloadfailure -> app.db", "app.db.models.downloadfailure -> app.db.base", "app.db.models.downloadfailure -> app.db.models", @@ -6959,6 +7034,19 @@ "app.db.oper.agenttask -> app.db.models", "app.db.oper.agenttask -> app.db.models.agenttask", "app.db.oper.agenttask -> app.db.models.agenttaskrun", + "app.db.oper.authorization -> app.db", + "app.db.oper.authorization -> app.db.models", + "app.db.oper.authorization -> app.db.models.agenttask", + "app.db.oper.authorization -> app.db.models.authorization", + "app.db.oper.authorization -> app.db.models.downloadhistory", + "app.db.oper.authorization -> app.db.models.subscribe", + "app.db.oper.authorization -> app.db.models.subscribehistory", + "app.db.oper.authorization -> app.db.models.systemconfig", + "app.db.oper.authorization -> app.db.models.user", + "app.db.oper.authorization -> app.domain", + "app.db.oper.authorization -> app.domain.authorization", + "app.db.oper.authorization -> app.schemas", + "app.db.oper.authorization -> app.schemas.types", "app.db.oper.downloadfailure -> app.db", "app.db.oper.downloadfailure -> app.db.base", "app.db.oper.downloadfailure -> app.db.models", @@ -7162,6 +7250,8 @@ "app.doctor.runner -> app.runtime", "app.doctor.runner -> app.runtime.settings", "app.doctor.runner -> app.runtime.version", + "app.domain.authorization -> app.schemas", + "app.domain.authorization -> app.schemas.types", "app.domain.classification.conditions -> app.schemas", "app.domain.classification.conditions -> app.schemas.category", "app.domain.classification.evaluator -> app.schemas", @@ -7410,6 +7500,8 @@ "app.modules._base.notification -> app.application.messaging", "app.modules._base.notification -> app.application.messaging.channel", "app.modules._base.notification -> app.application.messaging.channel.admin", + "app.modules._base.notification -> app.application.security", + "app.modules._base.notification -> app.application.security.authorization", "app.modules._base.notification -> app.foundation", "app.modules._base.notification -> app.foundation.collections", "app.modules._base.notification -> app.modules", @@ -7669,6 +7761,7 @@ "app.modules.feishu.feishu -> app.application.messaging.channel.admin", "app.modules.feishu.feishu -> app.application.messaging.ingress", "app.modules.feishu.feishu -> app.application.security", + "app.modules.feishu.feishu -> app.application.security.authorization", "app.modules.feishu.feishu -> app.application.security.user", "app.modules.feishu.feishu -> app.domain", "app.modules.feishu.feishu -> app.domain.context", @@ -8724,6 +8817,8 @@ "app.modules.telegram.module -> app.application.messaging", "app.modules.telegram.module -> app.application.messaging.channel", "app.modules.telegram.module -> app.application.messaging.channel.admin", + "app.modules.telegram.module -> app.application.security", + "app.modules.telegram.module -> app.application.security.authorization", "app.modules.telegram.module -> app.domain", "app.modules.telegram.module -> app.domain.context", "app.modules.telegram.module -> app.modules", @@ -10563,11 +10658,13 @@ "app.startup.composition.security -> app.application.configuration", "app.startup.composition.security -> app.application.security", "app.startup.composition.security -> app.application.security.auth", + "app.startup.composition.security -> app.application.security.authorization", "app.startup.composition.security -> app.application.security.passkey", "app.startup.composition.security -> app.application.security.user", "app.startup.composition.security -> app.application.security.widget", "app.startup.composition.security -> app.db", "app.startup.composition.security -> app.db.adapters", + "app.startup.composition.security -> app.db.adapters.authorization", "app.startup.composition.security -> app.db.adapters.user", "app.startup.composition.security -> app.db.adapters.widget", "app.startup.composition.security -> app.db.oper", @@ -11211,7 +11308,7 @@ "app.workflow.actions.transfer_file -> app.workflow", "app.workflow.actions.transfer_file -> app.workflow.actions" ], - "module_count": 1171, + "module_count": 1178, "modules": [ "app", "app.adapters", @@ -11431,6 +11528,7 @@ "app.api.endpoints.anilist", "app.api.endpoints.anthropic", "app.api.endpoints.auth", + "app.api.endpoints.authorization", "app.api.endpoints.bangumi", "app.api.endpoints.classification", "app.api.endpoints.dashboard", @@ -11597,6 +11695,7 @@ "app.application.search.state", "app.application.security", "app.application.security.auth", + "app.application.security.authorization", "app.application.security.cookie", "app.application.security.image", "app.application.security.otp", @@ -11785,6 +11884,7 @@ "app.db", "app.db.adapters", "app.db.adapters.agent", + "app.db.adapters.authorization", "app.db.adapters.chain", "app.db.adapters.classification", "app.db.adapters.configuration", @@ -11826,6 +11926,7 @@ "app.db.models.agentinvocation", "app.db.models.agenttask", "app.db.models.agenttaskrun", + "app.db.models.authorization", "app.db.models.downloadfailure", "app.db.models.downloadhistory", "app.db.models.mediaserver", @@ -11858,6 +11959,7 @@ "app.db.oper.agentchat", "app.db.oper.agentinvocation", "app.db.oper.agenttask", + "app.db.oper.authorization", "app.db.oper.downloadfailure", "app.db.oper.downloadhistory", "app.db.oper.mediaserver", @@ -11899,6 +12001,7 @@ "app.doctor.runner", "app.domain", "app.domain.artwork", + "app.domain.authorization", "app.domain.chat", "app.domain.classification", "app.domain.classification.conditions", @@ -12245,6 +12348,7 @@ "app.scheduler.services", "app.schemas", "app.schemas.agent", + "app.schemas.authorization", "app.schemas.cache", "app.schemas.calendar", "app.schemas.category", diff --git a/tests/fixtures/architecture/startup-performance-baseline.json b/tests/fixtures/architecture/startup-performance-baseline.json index ce7a17041..6dd6af628 100644 --- a/tests/fixtures/architecture/startup-performance-baseline.json +++ b/tests/fixtures/architecture/startup-performance-baseline.json @@ -6,7 +6,7 @@ "repeat": 3, "targets": { "app.startup.lifecycle": { - "loaded_app_module_count": 608, + "loaded_app_module_count": 613, "max_ms": 1293.338, "median_ms": 1156.239, "min_ms": 1102.806, @@ -17,7 +17,7 @@ ] }, "app.factory": { - "loaded_app_module_count": 622, + "loaded_app_module_count": 627, "max_ms": 1127.911, "median_ms": 1122.382, "min_ms": 1119.221, @@ -28,7 +28,7 @@ ] }, "app.main": { - "loaded_app_module_count": 624, + "loaded_app_module_count": 629, "max_ms": 1188.652, "median_ms": 1183.509, "min_ms": 1174.522, diff --git a/tests/test_auth_contracts.py b/tests/test_auth_contracts.py index 52decae9f..31a781bbd 100644 --- a/tests/test_auth_contracts.py +++ b/tests/test_auth_contracts.py @@ -303,7 +303,7 @@ def test_missing_current_user_is_unauthorized(): with pytest.raises(HTTPException) as exc_info: auth_dependencies.get_current_user( db=object(), - token_data=SimpleNamespace(sub=7), + token_data=TokenPayload(sub=7), runtime=runtime, ) @@ -761,6 +761,10 @@ def test_auth_exchange_sets_resource_cookie(): # 资源令牌不携带宿主 Agent 的渠道声明 "agent_channel": None, "agent_channel_user": None, + "agent_authorization_id": None, + "agent_operation": None, + "agent_method": None, + "agent_path": None, } diff --git a/tests/test_builtin_skill_boundaries.py b/tests/test_builtin_skill_boundaries.py index 20b28105a..1a0d6e93d 100644 --- a/tests/test_builtin_skill_boundaries.py +++ b/tests/test_builtin_skill_boundaries.py @@ -127,10 +127,10 @@ def test_modified_builtin_skills_have_incremented_versions() -> None: expected_versions = { "browser-use": "4", "command-dispatch": "2", - "database-operation": "19", + "database-operation": "20", "feedback-issue": "12", "anysearch": "3", - "moviepilot-api": "76", + "moviepilot-api": "77", "moviepilot-update": "7", "organize-files": "6", "transfer-failed-retry": "7", diff --git a/tests/test_channel_authorization.py b/tests/test_channel_authorization.py new file mode 100644 index 000000000..860592965 --- /dev/null +++ b/tests/test_channel_authorization.py @@ -0,0 +1,611 @@ +""" +统一渠道授权的身份隔离、实时撤销、API 令牌约束与审批交互回归。 +""" + +import asyncio +import json +from functools import partial +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock + +import pytest +from fastapi import HTTPException +from sqlalchemy import delete, select + +from app.agent.api.executor import ApiExecutionContext, ApiExecutionError, MoviePilotApiExecutor +from app.agent.identity import AgentIdentityError, require_execution_user, resolve_task_user +from app.application.security import authorization as authorization_module +from app.application.security.auth import AuthService +from app.application.security.authorization import ChannelAuthorizationService +from app.chain.message import MessageChain +from app.db.adapters.authorization import authorization_scope +from app.db.adapters.user import TransactionalUserRepository +from app.db.models.authorization import ChannelAuthorization, ChannelBinding +from app.db.models.user import User +from app.db.session import SessionFactory, async_session_scope +from app.schemas.system import NotificationConf +from app.schemas.token import TokenPayload +from app.schemas.types import NotificationChannel + + +@pytest.fixture +def channel_authorization(db, monkeypatch): + """ + 装配真实临时数据库授权服务,恢复进程服务并清理新增成员和内部账号。 + + :param db: 共享隔离库的水位清理工具 + :param monkeypatch: 当前用例的配置函数替换工具 + :yields: 授权服务、启用渠道配置及真实用户仓储 + """ + db.watermark(User) + configs = [ + NotificationConf(id="telegram-a", name="机器人A", type="telegram", enabled=True), + NotificationConf(id="telegram-b", name="机器人B", type="telegram", enabled=True), + NotificationConf(id="wechat-a", name="微信A", type="wechatclawbot", enabled=True), + ] + monkeypatch.setattr( + authorization_module, "get_notification_configs", lambda **_: [item for item in configs if item.enabled] + ) + service = ChannelAuthorizationService(partial(authorization_scope, SessionFactory)) + previous = authorization_module.get_channel_authorization() + authorization_module.configure_channel_authorization(service) + with SessionFactory() as session: + before = set(session.scalars(select(ChannelAuthorization.id))) + users = TransactionalUserRepository(sync_session=SessionFactory, async_session=async_session_scope) + try: + yield service, configs, users + finally: + authorization_module.configure_channel_authorization(previous) + with SessionFactory() as session: + session.execute(delete(ChannelBinding)) + statement = delete(ChannelAuthorization) + if before: + statement = statement.where(ChannelAuthorization.id.not_in(before)) + session.execute(statement) + session.commit() + + +def _approve(service, source="机器人A", sender_id="42", role="member", scopes=("search", "subscribe", "download")): + """ + 通过真实审批事务批准合成渠道发送者。 + """ + member = service.request(NotificationChannel.Telegram.value, source, sender_id, "测试成员") + return service.update(member.id, status="approved", role=role, scopes=scopes, reviewer_id=1) + + +def test_member_request_needs_no_login_and_repeated_request_cannot_restore_access(channel_authorization): + """ + 普通申请没有登录凭据,重复请求幂等且不能覆盖停用和拒绝决定。 + """ + service, _, users = channel_authorization + member = service.request("Telegram", "机器人A", "42", "普通成员") + assert member.status == "pending" + user = asyncio.run(users.async_get_by_id(member.user_id)) + assert user.account_type == "channel" + assert users.get_auth_by_name(user.name) is None + with pytest.raises(PermissionError, match="尚未授权"): + service.principal(member.id) + service.update(member.id, status="disabled", role="member", scopes=("search",), reviewer_id=1) + repeated = service.request("Telegram", "机器人A", "42", "伪装管理员") + assert repeated.id == member.id and repeated.status == "disabled" + assert repeated.display_name == "普通成员" + + +def test_same_sender_has_separate_instance_authority_and_rename_preserves_identity(channel_authorization): + """ + 相同平台 ID 的不同机器人分别授权,改名保留授权,删停和类型替换立即失权。 + """ + service, configs, _ = channel_authorization + admin = _approve(service, role="admin") + member = _approve(service, source="机器人B") + assert admin.user_id != member.user_id + assert service.is_admin("Telegram", "机器人A", "42") + assert not service.is_admin("Telegram", "机器人B", "42") + configs[0].name = "已改名" + assert service.resolve("Telegram", "已改名", "42").authorization_id == admin.id + configs[0].enabled = False + with pytest.raises(PermissionError, match="渠道"): + service.principal(admin.id) + assert service.principal(member.id).authorization_id == member.id + + +def test_role_and_scopes_are_rechecked_for_existing_api_executors(channel_authorization): + """ + 已构造的管理员执行器不能在降权或停用后继续使用旧权限。 + """ + service, _, _ = channel_authorization + member = _approve(service, role="admin") + user = service.principal(member.id) + executor = MoviePilotApiExecutor( + context=ApiExecutionContext(user_id=str(user.id), username=user.name, is_admin=True, authorization_id=member.id) + ) + assert executor._build_headers("site.list", "GET", "/api/v1/site/")["Authorization"].startswith("Bearer ") + service.update(member.id, status="approved", role="member", scopes=("search",), reviewer_id=1) + with pytest.raises(ApiExecutionError, match="没有此操作"): + executor._build_headers("site.list", "GET", "/api/v1/site/") + with pytest.raises(PermissionError): + service.authorize_operation(member.id, "subscription.add") + assert service.authorize_operation(member.id, "media.detail").authorization_id == member.id + service.update(member.id, status="disabled", role="member", scopes=("search",), reviewer_id=1) + with pytest.raises(ApiExecutionError, match="停用"): + executor._build_headers("search.torrents", "GET", "/api/v1/search/media/1") + + +def test_channel_token_has_fixed_route_and_cannot_issue_web_login(channel_authorization): + """ + 渠道令牌带固定路由声明,账号不能取得网页登录令牌,撤销后旧签名也被拒绝。 + """ + from app.application.security.token import decode_access_token + + service, _, users = channel_authorization + member = _approve(service) + user = service.principal(member.id) + executor = MoviePilotApiExecutor( + context=ApiExecutionContext( + user_id=str(user.id), username=user.name, is_admin=False, authorization_id=member.id + ) + ) + token = executor._build_headers("subscription.list", "GET", "/api/v1/subscribe/")["Authorization"].split(" ", 1)[1] + payload = decode_access_token(token) + assert payload.agent_authorization_id == member.id + assert payload.agent_method == "GET" and payload.agent_path == "/api/v1/subscribe/" + auth = AuthService(users=users, config=Mock(), passkeys=Mock()) + auth.validate_token_identity(payload) + with pytest.raises(PermissionError, match="不可网页登录"): + auth.build_token_response(user) + with pytest.raises(PermissionError, match="网页登录"): + auth.validate_token_identity(TokenPayload(sub=user.id, username=user.name, super_user=False)) + service.update(member.id, status="disabled", role="member", scopes=(), reviewer_id=1) + with pytest.raises(PermissionError): + auth.validate_token_identity(payload) + + +def test_scheduled_tasks_preserve_authorization_and_recheck_schedule_permission(channel_authorization): + """ + 渠道定时任务固定执行主体,撤销调度能力后不再允许后台执行。 + """ + service, _, users = channel_authorization + member = _approve(service, scopes=("search", "schedule")) + user = asyncio.run( + resolve_task_user( + users, user_id="42", username="管理员同名", channel="Telegram", source="机器人A", is_admin=False + ) + ) + assert user.authorization_id == member.id + assert ( + asyncio.run(require_execution_user(users, user.id, user.notification_identity, member.id, "schedule")).id + == user.id + ) + service.update(member.id, status="approved", role="member", scopes=("search",), reviewer_id=1) + with pytest.raises(AgentIdentityError, match="schedule"): + asyncio.run(require_execution_user(users, user.id, user.notification_identity, member.id, "schedule")) + + +def test_deleted_account_id_reuse_cannot_inherit_channel_authorization(channel_authorization): + """ + 账号主键被重用时,不可变身份阻止旧授权被新账号继承。 + """ + service, _, _ = channel_authorization + member = _approve(service) + with SessionFactory() as session: + user = session.get(User, member.user_id) + user.notification_identity = "replaced-identity" + session.commit() + with pytest.raises(PermissionError, match="账号"): + service.principal(member.id) + + +def test_apply_control_is_handled_without_model_and_does_not_run_old_request(channel_authorization, monkeypatch): + """ + 申请按钮和文本共用确定性入口,不经过模型或自动执行先前写入。 + """ + service, _, _ = channel_authorization + chain = MessageChain() + post = Mock() + monkeypatch.setattr(chain, "post_message", post) + assert chain._handle_channel_authorization( + NotificationChannel.Telegram, "机器人A", "42", "成员", "订阅某部电影", None + ) + assert post.call_args.args[0].buttons[0][0]["callback_data"] == "authorization:apply" + assert chain._handle_channel_authorization( + NotificationChannel.Telegram, "机器人A", "42", "成员", "", "authorization:apply" + ) + assert service.find("Telegram", "机器人A", "42").status == "pending" + assert post.call_count == 3 + + +def test_channel_admin_cannot_manage_public_authorizations(): + """ + 渠道管理员不等于网页登录系统管理员,不能从新管理端点继续转授权限。 + """ + from app.api.endpoints.authorization import _administrator + + with pytest.raises(HTTPException) as error: + _administrator(SimpleNamespace(is_superuser=True, account_type="channel", authorization_id="member")) + assert error.value.status_code == 403 + + +@pytest.mark.parametrize("status", ["pending", "approved"]) +def test_channel_member_text_cannot_reenter_legacy_admin_sessions(channel_authorization, monkeypatch, status): + """ + 普通及待审批成员绕过旧插件输入会话,只把业务请求送到受控 Agent。 + """ + from dataclasses import replace + + service, _, _ = channel_authorization + if status == "approved": + _approve(service, scopes=("search",)) + else: + service.request("Telegram", "机器人A", "42", "成员") + chain = MessageChain() + monkeypatch.setattr( + chain, "runtime_config", replace(chain.runtime_config, ai_agent_enable=True, ai_agent_global=True) + ) + agent = Mock(return_value=False) + plugin = Mock() + monkeypatch.setattr(chain, "_handle_ai_message", agent) + monkeypatch.setattr(chain, "_plugin_input_interaction_handler", plugin) + monkeypatch.setattr(chain, "_handle_secret_confirmation_control", Mock(return_value=False)) + monkeypatch.setattr(chain, "_mark_message_processing_finished", Mock()) + chain.handle_message(NotificationChannel.Telegram, "机器人A", "42", "昵称", "继续操作", is_channel_admin=True) + assert agent.call_args.kwargs["is_channel_admin"] is False + plugin.assert_not_called() + if status == "approved": + post = Mock() + monkeypatch.setattr(chain, "post_message", post) + assert chain._handle_channel_authorization( + NotificationChannel.Telegram, "机器人A", "42", "昵称", "", "system:restart" + ) + assert "管理员" in post.call_args.args[0].title + + +def test_account_binding_requires_both_sides_and_never_approves_pending_member(channel_authorization, db): + """ + 网页账号生成的码只能消费一次,关联不会替代渠道审批或解除管理员停用。 + """ + service, _, _ = channel_authorization + local = db.add( + User( + name="bound-web-account", + is_active=True, + is_superuser=False, + settings={}, + permissions={"search": True, "subscribe": True, "manage": True}, + ) + ) + code, _ = service.create_binding(local.id) + member = service.bind("Telegram", "机器人A", "42", "成员", code) + assert member.user_id == local.id and member.linked_user_id == local.id + assert member.status == "pending" + with pytest.raises(ValueError, match="无效"): + service.bind("Telegram", "机器人B", "43", "其它成员", code) + member = service.update(member.id, status="approved", role="member", scopes=("search", "subscribe"), reviewer_id=1) + assert service.principal(member.id).name == local.name + assert service.principal(member.id).permissions["download"] is False + service.update(member.id, status="disabled", role="member", scopes=("search",), reviewer_id=1) + new_code, _ = service.create_binding(local.id) + assert service.bind("Telegram", "机器人A", "42", "成员", new_code).status == "disabled" + + +def test_binding_expiry_and_replaced_account_fail_without_changing_member(channel_authorization, db, monkeypatch): + """ + 到期和网页账号被替换时,关联失败不改变渠道成员业务归属。 + """ + service, _, _ = channel_authorization + local = db.add(User(name="binding-expiry", is_active=True, is_superuser=False)) + member = service.request("Telegram", "机器人A", "42", "成员") + code, expires_at = service.create_binding(local.id) + monkeypatch.setattr(authorization_module.time, "time", lambda: expires_at + 1) + with pytest.raises(ValueError, match="过期"): + service.bind("Telegram", "机器人A", "42", "成员", code) + assert service.find("Telegram", "机器人A", "42").user_id == member.user_id + + +def test_channel_tokens_cannot_be_reused_for_other_paths(channel_authorization, monkeypatch): + """ + 同一签名令牌不能从只读订阅路径转用到其它 API,且不会下发网页登录 Cookie。 + """ + from starlette.requests import Request + from starlette.responses import Response + + from app.adapters.web.security import access + + service, _, _ = channel_authorization + member = _approve(service) + user = service.principal(member.id) + payload = TokenPayload( + sub=user.id, + username=user.name, + super_user=False, + agent_authorization_id=member.id, + agent_operation="subscription.list", + agent_method="GET", + agent_path="/api/v1/subscribe/", + ) + monkeypatch.setattr(access, "_decode_or_http_error", lambda *_: payload) + monkeypatch.setattr(access, "_token_identity_validator", lambda _: None) + cookie = Mock() + monkeypatch.setattr(access, "set_or_refresh_resource_token_cookie", cookie) + valid = Request({"type": "http", "method": "GET", "path": "/api/v1/subscribe/", "headers": []}) + assert access.verify_token(valid, Response(), "token", None, None) == payload + cookie.assert_not_called() + invalid = Request({"type": "http", "method": "POST", "path": "/api/v1/user/", "headers": []}) + with pytest.raises(HTTPException) as error: + access.verify_token(invalid, Response(), "token", None, None) + assert error.value.status_code == 403 + + +@pytest.mark.parametrize( + "channel_type", + ["telegram", "wechat", "wechatclawbot", "feishu", "qqbot", "discord", "slack", "vocechat", "synologychat"], +) +def test_every_channel_uses_common_grants_instead_of_legacy_keys(channel_authorization, channel_type): + """ + 各平台管理员都读取公共授权,旧名单和默认投递接收人不能恢复已撤销的权限。 + """ + from app.application.messaging.channel.admin import matches_channel_admin + from app.domain.authorization import LEGACY_CHANNELS + + service, configs, _ = channel_authorization + channel, _, admin_key, primary_key = LEGACY_CHANNELS[channel_type] + config = NotificationConf( + id=f"legacy-{channel_type}", + name=f"{channel_type}-bot", + type=channel_type, + enabled=True, + config={admin_key: "sender", primary_key: "sender"}, + ) + configs.append(config) + assert not matches_channel_admin(channel, config.config, "sender", source=config.name) + member = service.request(channel, config.name, "sender", "管理员") + service.update(member.id, status="approved", role="admin", scopes=(), reviewer_id=1) + assert matches_channel_admin(channel, config.config, "sender", source=config.name) + service.update(member.id, status="disabled", role="admin", scopes=(), reviewer_id=1) + assert not matches_channel_admin(channel, config.config, "sender", source=config.name) + + +def test_concurrent_duplicate_requests_create_one_member_and_one_internal_user(channel_authorization): + """ + 两个真实线程同时申请时,数据库锁保证身份唯一且没有孤立内部账号。 + """ + from concurrent.futures import ThreadPoolExecutor + from threading import Barrier + + service, _, _ = channel_authorization + barrier = Barrier(2) + with SessionFactory() as session: + before = set(session.scalars(select(User.id))) + + def request(): + """ + 同步释放两个并发请求,使查重与创建发生真实竞争。 + """ + barrier.wait(timeout=5) + return service.request("Telegram", "机器人A", "42", "成员") + + with ThreadPoolExecutor(max_workers=2) as pool: + futures = [pool.submit(request) for _ in range(2)] + members = [future.result(timeout=10) for future in futures] + assert members[0].id == members[1].id + with SessionFactory() as session: + assert len(set(session.scalars(select(User.id))) - before) == 1 + + +def test_approval_api_enforces_administrator_and_returns_sanitized_contract(channel_authorization, monkeypatch): + """ + 通过真实 ASGI 端点验证批准、停用、非法范围拒绝及内部凭据不出现在响应中。 + """ + from fastapi import FastAPI + from fastapi.testclient import TestClient + + from app.api.dependencies.auth import get_current_active_superuser + from app.api.endpoints import authorization as endpoint + + service, configs, _ = channel_authorization + member = service.request("Telegram", "机器人A", "42", "成员") + monkeypatch.setattr(endpoint, "get_notification_configs", lambda **_: configs) + monkeypatch.setattr(endpoint, "_notify", Mock()) + app = FastAPI() + app.include_router(endpoint.router, prefix="/authorization") + app.dependency_overrides[get_current_active_superuser] = lambda: SimpleNamespace( + id=1, account_type="local", authorization_id=None + ) + with TestClient(app) as client: + response = client.get("/authorization/") + assert response.status_code == 200 + assert response.json()["data"]["members"][0]["status"] == "pending" + assert "user_identity" not in response.text and "user_id" not in response.text + assert ( + client.put( + f"/authorization/{member.id}", + json={"status": "approved", "role": "member", "scopes": ["search", "subscribe"]}, + ).status_code + == 200 + ) + assert service.principal(member.id).permissions["subscribe"] is True + assert ( + client.put(f"/authorization/{member.id}", json={"status": "approved", "scopes": ["unknown"]}).status_code + == 422 + ) + assert client.put(f"/authorization/{member.id}", json={"status": "disabled", "scopes": []}).status_code == 200 + with pytest.raises(PermissionError): + service.principal(member.id) + app.dependency_overrides[get_current_active_superuser] = lambda: SimpleNamespace( + id=1, account_type="channel", authorization_id=member.id + ) + assert client.get("/authorization/").status_code == 403 + + +def test_disabled_member_cannot_run_nonbase_tools_or_subagent_tools(channel_authorization): + """ + 已构建的策略中间件在撤销后阻止非基础记忆工具和子代理继续执行。 + """ + from app.agent.middleware.policy import AgentPolicyMiddleware + from app.agent.policy.contracts import AuthSource, PrincipalType, ToolOrigin, ToolPolicyContext + + service, _, _ = channel_authorization + member = _approve(service) + context = {"authorization_id": member.id, "is_admin": True} + middleware = AgentPolicyMiddleware( + context=ToolPolicyContext( + session_id="session", + user_id="42", + origin=ToolOrigin.SUBAGENT, + principal_type=PrincipalType.SUBAGENT, + auth_source=AuthSource.CHANNEL, + agent_context=context, + ) + ) + handler = AsyncMock(return_value="不应执行") + service.update(member.id, status="disabled", role="member", scopes=(), reviewer_id=1) + allowed, result = asyncio.run( + middleware.execute_tool_call(tool=SimpleNamespace(name="memory_read"), arguments={}, handler=handler) + ) + assert allowed is False and result.status == "error" + handler.assert_not_awaited() + + +def test_channel_binding_code_is_redacted_from_all_host_log_outputs(monkeypatch): + """ + SDK 记录入站正文时,一次性关联码在文件与控制台出口前被隐藏。 + """ + from app.runtime.log import LoggerManager + + manager = LoggerManager() + writer = Mock() + console = Mock() + monkeypatch.setattr(manager, "_write_file_log", writer) + monkeypatch.setattr(manager, "_get_console_logger", lambda _: console) + manager.info("收到消息:%s", "绑定账号 synthetic_binding_credential_12345") + assert "synthetic_binding_credential_12345" not in str(writer.call_args) + assert "synthetic_binding_credential_12345" not in str(console.info.call_args) + assert "已隐藏" in str(writer.call_args) + + +def test_channel_task_tool_accepts_schedule_grant_and_keeps_instance_ownership(channel_authorization, db, monkeypatch): + """ + 获调度能力的普通成员能创建任务,任务与运行快照固定同一授权且跨实例不可见。 + """ + from app.agent.tools.impl.agent_task import AgentTaskTool + from app.application import scheduling + from app.db.adapters.agent import TransactionalAgentTaskRepository + from app.db.models.agenttask import AgentTask + from app.db.models.agenttaskrun import AgentTaskRun + + service, _, users = channel_authorization + db.watermark(AgentTask, AgentTaskRun) + first = _approve(service, scopes=("search", "schedule")) + second = _approve(service, source="机器人B", scopes=("search", "schedule")) + tasks = TransactionalAgentTaskRepository(SessionFactory) + data = SimpleNamespace(users=users, tasks=tasks, chat=SimpleNamespace(get_sync=Mock(return_value=None))) + tool = AgentTaskTool(session_id="channel-task", user_id="42", data=data) + tool.set_message_attr(channel="Telegram", source="机器人A", username="成员") + tool.set_agent_context({"authorization_id": first.id, "is_admin": False}) + monkeypatch.setattr(scheduling, "update_agent_task_job", lambda _: None) + monkeypatch.setattr( + "app.agent.tools.impl.agent_task.get_runtime_setting", + lambda name: True if name == "AI_AGENT_ENABLE" else "Asia/Shanghai", + ) + result = json.loads( + asyncio.run( + tool.run(action="create", name="渠道测试", content="查询公共资料", trigger_type="date", delay_minutes=10) + ) + ) + task = tasks.get(task_id=result["id"], user_id=f"channel:{first.id}") + assert task.execution_authorization_id == first.id and task.execution_user_id == first.user_id + assert tasks.get(task_id=result["id"], user_id=f"channel:{second.id}") is None + run = tasks.begin_run(task_id=task.id, trigger_source="manual") + assert run.execution_authorization_id == first.id + + +def test_channel_download_pagination_filters_before_count_and_page(channel_authorization, db): + """ + 下载历史在数据库分页前按归属收窄,总数和页面都不泄露其它成员的记录。 + """ + from app.db.adapters.history.download import TransactionalDownloadHistoryRepository + from app.db.models.downloadhistory import DownloadHistory + + service, _, _ = channel_authorization + first = service.principal(_approve(service).id) + second = service.principal(_approve(service, source="机器人B").id) + db.add( + DownloadHistory( + path="/synthetic/first.mkv", + type="电影", + title="自己的下载", + username=first.name, + date="2026-11-16 10:00:00", + ), + DownloadHistory( + path="/synthetic/second.mkv", + type="电影", + title="别人的下载", + username=second.name, + date="2026-11-17 10:00:00", + ), + ) + repository = TransactionalDownloadHistoryRepository(sync_session=SessionFactory, async_session=async_session_scope) + records = asyncio.run(repository.async_list_by_page(1, 1, username=first.name)) + assert [record.title for record in records] == ["自己的下载"] + assert asyncio.run(repository.async_count(username=first.name)) == 1 + + +def test_scheduled_execution_uses_current_delivery_and_stops_after_revocation(channel_authorization, db, monkeypatch): + """ + 真实任务执行在渠道改名后仍私聊原成员,撤销能力和未确认旧身份均终结为失败。 + """ + from app.agent.manager import AgentManager + from app.chain.agent import AgentChain + from app.db.models.agenttask import AgentTask + from app.db.models.agenttaskrun import AgentTaskRun + from app.db.oper.agenttask import AgentTaskOper + from app.runtime.config import settings + + service, configs, users = channel_authorization + db.watermark(AgentTask, AgentTaskRun) + member = _approve(service, scopes=("search", "schedule")) + task = AgentTaskOper().add( + name="已授权渠道任务", + content="查询公共资料", + trigger_type="cron", + cron_expression="0 * * * *", + user_id=f"channel:{member.id}", + username="成员", + session_id="channel-scheduled-test", + channel="Telegram", + source="机器人A", + original_chat_id="旧群聊", + execution_user_id=member.user_id, + execution_user_identity=member.user_identity, + execution_authorization_id=member.id, + ) + process = AsyncMock(return_value="执行完成") + manager = SimpleNamespace(_accepting_tasks=True, _data=SimpleNamespace(users=users), process_message=process) + monkeypatch.setattr(settings, "AI_AGENT_ENABLE", True) + monkeypatch.setattr(AgentChain, "async_post_message", AsyncMock()) + configs[0].name = "已改名" + assert asyncio.run(AgentManager.execute_scheduled_task(manager, task.id)) == (True, "执行完成") + context = process.await_args.kwargs + assert context["user_id"] == "42" and context["source"] == "已改名" + assert context["channel"] == "Telegram" and context["original_chat_id"] is None + assert context["authorization_id"] == member.id and context["execution_user_id"] == member.user_id + process.reset_mock() + service.update(member.id, status="approved", role="member", scopes=("search",), reviewer_id=1) + success, result = asyncio.run(AgentManager.execute_scheduled_task(manager, task.id)) + assert success is False and "schedule" in result + process.assert_not_awaited() + assert AgentTaskOper().get(task.id).last_status == "failed" + AgentTaskOper().update(task.id, user_id=task.user_id, payload={"execution_authorization_id": None}) + success, result = asyncio.run(AgentManager.execute_scheduled_task(manager, task.id)) + assert success is False and "旧任务尚未确认渠道授权" in result + process.assert_not_awaited() + + +def test_authorization_public_operations_match_the_audited_gateway_contract(): + """ + 渠道权限的公共清单与 API 已审计清单精确一致,不能误将只读私密数据放行。 + """ + from app.agent.policy.api import API_UNBOUND_READ_OPERATIONS + from app.domain.authorization import CHANNEL_PUBLIC_OPERATIONS + + assert CHANNEL_PUBLIC_OPERATIONS == API_UNBOUND_READ_OPERATIONS diff --git a/tests/test_channel_authorization_migration.py b/tests/test_channel_authorization_migration.py new file mode 100644 index 000000000..52e8f6c37 --- /dev/null +++ b/tests/test_channel_authorization_migration.py @@ -0,0 +1,141 @@ +""" +统一授权迁移对旧用户、管理员、默认接收人和重复绑定的离线验证。 +""" + +import importlib + +import pytest +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + +from app.db.models.authorization import ChannelAuthorization +from app.db.models.user import User +from app.domain.authorization import LEGACY_CHANNELS + + +def _tables(connection): + """ + 在独立 SQLite 连接中创建迁移所需旧表,不接触共享测试库。 + """ + metadata = sa.MetaData() + User.__table__.to_metadata(metadata) + system = sa.Table( + "systemconfig", + metadata, + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("key", sa.String()), + sa.Column("value", sa.JSON()), + ) + for name in ("agenttask", "agenttaskrun"): + sa.Table(name, metadata, sa.Column("id", sa.Integer(), primary_key=True), sa.Column("username", sa.String())) + metadata.create_all(connection) + return metadata.tables["user"], system + + +@pytest.mark.parametrize("channel_type,definition", LEGACY_CHANNELS.items()) +def test_legacy_lists_migrate_per_instance_and_only_once(monkeypatch, channel_type, definition): + """ + 每个渠道完整迁移普通与管理员名单,主接收人保留但不会被重复导入覆盖新授权。 + """ + migration = importlib.import_module("database.versions.d8a4c6e29170_channel_authorization") + engine = sa.create_engine("sqlite://") + channel, users_key, admins_key, primary_key = definition + values = {admins_key: " admin , overlap,admin ", "unrelated": "保留的配置"} + if users_key: + values[users_key] = "member,overlap" + if primary_key: + values[primary_key] = "primary" + if channel_type == "wechat": + values["WECHAT_MODE"] = "bot" + with engine.begin() as connection: + _, system = _tables(connection) + connection.execute( + system.insert().values( + id=1, + key="Notifications", + value=[ + {"id": "first", "name": "渠道A", "type": channel_type, "enabled": True, "config": values}, + { + "id": "second", + "name": "渠道B", + "type": channel_type, + "enabled": False, + "config": {admins_key: "member"}, + }, + ], + ) + ) + monkeypatch.setattr(migration, "op", Operations(MigrationContext.configure(connection))) + migration.upgrade() + members = sa.Table("channelauthorization", sa.MetaData(), autoload_with=connection) + rows = list(connection.execute(sa.select(members)).mappings()) + first = {row["sender_id"]: row for row in rows if row["notification_id"] == "first"} + assert first["admin"]["role"] == "admin" and first["overlap"]["role"] == "admin" + assert all(row["channel"] == channel for row in rows) + if users_key: + assert first["member"]["role"] == "member" + if primary_key: + assert first["primary"]["role"] == "admin" + assert next(row for row in rows if row["notification_id"] == "second")["role"] == "admin" + persisted = connection.execute(sa.select(system.c.value)).scalar_one() + assert admins_key not in persisted[0]["config"] + assert not users_key or users_key not in persisted[0]["config"] + assert persisted[0]["config"]["unrelated"] == "保留的配置" + if primary_key: + assert persisted[0]["config"][primary_key] == "primary" + connection.execute(members.update().where(members.c.id == first["admin"]["id"]).values(status="disabled")) + migration.upgrade() + assert connection.execute(sa.select(sa.func.count()).select_from(members)).scalar_one() == len(rows) + assert ( + connection.execute(sa.select(members.c.status).where(members.c.id == first["admin"]["id"])).scalar_one() + == "disabled" + ) + assert "execution_authorization_id" in { + column["name"] for column in sa.inspect(connection).get_columns("agenttask") + } + + +def test_migration_reuses_unique_account_and_keeps_ambiguous_identity_pending(monkeypatch): + """ + 唯一旧绑定保留业务归属,重复绑定不猜测账号,停用渠道也不丢失名单。 + """ + migration = importlib.import_module("database.versions.d8a4c6e29170_channel_authorization") + engine = sa.create_engine("sqlite://") + with engine.begin() as connection: + users, system = _tables(connection) + for user_id, sender in ((1, "unique"), (2, "duplicate"), (3, "duplicate")): + connection.execute( + users.insert().values( + id=user_id, + name=f"user{user_id}", + account_type="local", + notification_identity=f"identity-{user_id}", + settings={"telegram_userid": sender}, + ) + ) + connection.execute( + system.insert().values( + id=1, + key="Notifications", + value=[ + { + "id": "telegram", + "name": "频道", + "type": "telegram", + "enabled": False, + "config": {"TELEGRAM_USERS": "unique,duplicate", "TELEGRAM_ADMINS": "admin"}, + }, + ], + ) + ) + monkeypatch.setattr(migration, "op", Operations(MigrationContext.configure(connection))) + migration.upgrade() + members = sa.Table("channelauthorization", sa.MetaData(), autoload_with=connection) + rows = {row["sender_id"]: row for row in connection.execute(sa.select(members)).mappings()} + assert rows["unique"]["user_id"] == 1 and rows["unique"]["user_identity"] == "identity-1" + assert rows["duplicate"]["status"] == "pending" and rows["duplicate"]["user_id"] not in {1, 2, 3} + assert rows["admin"]["role"] == "admin" + assert set(ChannelAuthorization.__table__.columns.keys()) == { + column["name"] for column in sa.inspect(connection).get_columns("channelauthorization") + } diff --git a/tests/test_subscription_identity_review_migration.py b/tests/test_subscription_identity_review_migration.py index 6a1a01c85..9d7c06e36 100644 --- a/tests/test_subscription_identity_review_migration.py +++ b/tests/test_subscription_identity_review_migration.py @@ -87,7 +87,8 @@ def test_identity_upgrade_chain_preserves_plugin_installation_snapshot(monkeypat config = Config() config.set_main_option("script_location", "database") script = ScriptDirectory.from_config(config) - assert script.get_heads() == ["b7c1e3d5f9a2"] + assert script.get_heads() == ["d8a4c6e29170"] + assert script.get_revision("d8a4c6e29170").down_revision == "b7c1e3d5f9a2" assert script.get_revision("b7c1e3d5f9a2").down_revision == "a7383c1d9e20" assert script.get_revision("a7383c1d9e20").down_revision == "b849e613a72f" assert script.get_revision("b849e613a72f").down_revision == "97ad7239c1e0"