diff --git a/app/agent/middleware/policy.py b/app/agent/middleware/policy.py
index 736324122..19f11383a 100644
--- a/app/agent/middleware/policy.py
+++ b/app/agent/middleware/policy.py
@@ -13,6 +13,7 @@ from langchain_core.messages import AIMessage, AnyMessage, ToolMessage
from app.agent.policy.api import resolve_api_operation
from app.agent.policy.contracts import (
ActionEffect,
+ AuthSource,
ExecutionOutcome,
ExecutionReceipt,
ToolOrigin,
@@ -31,6 +32,7 @@ from app.agent.tools.impl.api import MoviePilotApiTool
from app.agent.tools.impl.mcp import McpExternalTool
from app.agent.tools.result import EXECUTION_OUTCOME_KEY, ToolExecutionError, annotate_tool_result
from app.agent.tools.tags import ToolTag
+from app.schemas.types import NotificationChannel
if TYPE_CHECKING:
from app.agent.middleware.guardrails import ToolGuardrailsMiddleware
@@ -227,6 +229,8 @@ class AgentPolicyMiddleware(AgentMiddleware):
执行一次本地工具调用,并复用 ToolNode 的策略生命周期。
"""
authorization_error = await self._channel_authorization_error(tool, arguments)
+ if not authorization_error:
+ authorization_error = self._web_authorization_error(tool)
if authorization_error:
return False, ToolMessage(content=authorization_error, tool_call_id=str(invocation_id or ""),
name=str(getattr(tool, "name", "unknown")), status="error",
@@ -308,6 +312,31 @@ class AgentPolicyMiddleware(AgentMiddleware):
state["message"] = str(error)
return str(error)
+ def _web_authorization_error(self, tool: Any) -> str | None:
+ """
+ 对直接登录的网页会话复核账号激活状态及插件/管理员工具边界。
+
+ :param tool: 即将执行的本地工具实例
+ :return: 拒绝原因;放行时返回 None
+ """
+ is_web_session = self.context.auth_source is AuthSource.WEB_SESSION or (
+ self.context.channel in {NotificationChannel.Web.value, NotificationChannel.WebAgent.value}
+ and self.context.source not in {"api", "openai", "openai.responses", "anthropic"}
+ )
+ if not is_web_session:
+ return None
+ if self.context.agent_context.get("web_user_active") is False:
+ return "当前 MoviePilot 用户已停用,请联系管理员启用该用户后重试。"
+ if bool(self.context.agent_context.get("is_admin")):
+ return None
+ tool_source = str(getattr(tool, "_agent_tool_source", "") or "")
+ tool_name = str(getattr(tool, "name", "") or "")
+ if tool_source.startswith("plugin:") or tool_name.startswith("plugin:"):
+ return "此插件工具仅允许系统管理员调用。"
+ if getattr(tool, "_require_admin", getattr(tool, "require_admin", False)):
+ return "抱歉,您没有权限执行此操作(仅限系统管理员)。"
+ return None
+
@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 c44703285..f1e11d653 100644
--- a/app/agent/orchestrator.py
+++ b/app/agent/orchestrator.py
@@ -103,6 +103,11 @@ from app.application.messaging.chat import (
from app.application.messaging.recall import RecallSession
from app.application.plugin.runtime import get_plugin_manager
from app.chain.agent import AgentChain
+from app.domain.authorization import (
+ describe_web_permissions,
+ normalize_web_permissions,
+ web_permissions_signature,
+)
from app.foundation.identity import build_user_memory_key
from app.runtime.events import eventmanager
from app.runtime.execution import run_in_threadpool
@@ -1114,6 +1119,39 @@ class MoviePilotAgent:
"""
return bool(self.channel and self.source)
+ def _is_direct_web_session(self) -> bool:
+ """
+ 判断当前会话是否为直接登录用户的网页或 WebAgent 交互会话。
+
+ :return: 排除 OpenAI/Anthropic 协议集成入口后的直接网页会话返回 True
+ """
+ return (
+ self.channel in {NotificationChannel.Web.value, NotificationChannel.WebAgent.value}
+ and self.source not in {"openai", "openai.responses", "anthropic"}
+ )
+
+ async def _resolve_web_user(self) -> Any:
+ """
+ 按当前直接网页会话的用户标识实时查询用户记录。
+
+ 优先按数字 user_id 查询;无法解析或缺失时兼容旧版按 username 查询。
+
+ :return: 实时用户对象;未找到或数据上下文不可用时返回 None
+ """
+ if self._data is None:
+ return None
+ parsed_user_id = self._coerce_int(self.user_id)
+ try:
+ if parsed_user_id is not None and hasattr(self._data.users, "async_get_by_id"):
+ user = await self._data.users.async_get_by_id(parsed_user_id)
+ if user is not None:
+ return user
+ if self.username and hasattr(self._data.users, "async_get_by_name"):
+ return await self._data.users.async_get_by_name(self.username)
+ except Exception as e:
+ logger.error(f"查询网页会话用户信息失败: {e}")
+ return None
+
async def _is_system_admin_context(self) -> bool:
"""
判断当前 Agent 会话是否应按系统管理员上下文运行工具。
@@ -1152,22 +1190,17 @@ class MoviePilotAgent:
"anthropic",
}:
return True
- if self.channel and self.channel != NotificationChannel.Web.value:
+ if self.channel and self.channel not in {NotificationChannel.Web.value, NotificationChannel.WebAgent.value}:
return self.is_channel_admin is True
- if not self.username:
- return False
- try:
- if self._data is None:
- return False
- 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(local_user and local_user.is_superuser)
+ local_user = await self._resolve_web_user()
+ return bool(local_user and getattr(local_user, "is_active", True) is not False and local_user.is_superuser)
async def _build_tool_context(self, should_dispatch_reply: bool) -> Dict[str, object]:
"""
- 构造本轮工具共享上下文。
+ 构造本轮工具共享上下文,并绑定当前登录用户的实时权限快照。
+
+ :param should_dispatch_reply: 本轮是否需要向渠道派发回复
+ :return: 本轮工具共享上下文
"""
authorization_id = self.authorization_id
authorization_required = bool(authorization_id)
@@ -1179,11 +1212,45 @@ class MoviePilotAgent:
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
+
+ web_user_active: Optional[bool] = None
+ web_user_permissions: Optional[dict[str, Any]] = None
+ if (
+ self._is_direct_web_session()
+ and not self.is_background
+ and not authorization_id
+ and self.execution_user_id is None
+ ):
+ web_user = await self._resolve_web_user()
+ web_user_active = bool(web_user and getattr(web_user, "is_active", True) is not False)
+ is_admin = bool(web_user_active and web_user.is_superuser)
+ web_user_permissions = (
+ normalize_web_permissions(getattr(web_user, "permissions", None))
+ if web_user_active
+ else normalize_web_permissions(None)
+ )
+ else:
+ is_admin = await self._is_system_admin_context()
+ if self.execution_user_id is not None and self._is_direct_web_session():
+ execution_user = await require_execution_user(
+ self._data.users if self._data is not None else None,
+ self.execution_user_id,
+ self.execution_user_identity or "",
+ )
+ web_user_active = bool(getattr(execution_user, "is_active", True) is not False)
+ web_user_permissions = (
+ normalize_web_permissions(getattr(execution_user, "permissions", None))
+ if web_user_active
+ else normalize_web_permissions(None)
+ )
+
return {
"user_reply_sent": False,
"reply_mode": None,
"should_dispatch_reply": should_dispatch_reply,
- "is_admin": await self._is_system_admin_context(),
+ "is_admin": is_admin,
+ "web_user_active": web_user_active,
+ "web_user_permissions": web_user_permissions,
"execution_user_id": self.execution_user_id,
"execution_user_identity": self.execution_user_identity,
"authorization_id": authorization_id,
@@ -1839,6 +1906,72 @@ class MoviePilotAgent:
return tools
return [tool for tool in tools if getattr(tool, "name", None) != "search_web"]
+ @staticmethod
+ def _is_plugin_tool(tool: Any) -> bool:
+ """
+ 判断工具是否由插件动态注册。
+
+ :param tool: 待检查的工具实例
+ :return: 是否为插件来源工具
+ """
+ source = getattr(tool, "_agent_tool_source", None)
+ if isinstance(source, str) and source.startswith("plugin:"):
+ return True
+ name = getattr(tool, "name", None)
+ return isinstance(name, str) and name.startswith("plugin:")
+
+ @classmethod
+ def _filter_tools_for_principal(cls, tools: List[Any], *, is_admin: bool) -> List[Any]:
+ """
+ 非管理员会话不向模型暴露管理员工具与插件工具,避免模型产生管理员错觉。
+
+ :param tools: 原始工具列表
+ :param is_admin: 当前会话主体是否为系统管理员
+ :return: 过滤后的工具列表
+ """
+ if is_admin:
+ return list(tools)
+ return [
+ tool
+ for tool in tools
+ if not getattr(tool, "_require_admin", getattr(tool, "require_admin", False))
+ and not cls._is_plugin_tool(tool)
+ ]
+
+ def _effective_is_admin(self) -> bool:
+ """
+ 读取当前轮次是否处于管理员上下文;未显式构建上下文时仅内部后台与管理员协议入口视为管理员。
+
+ :return: 当前会话是否拥有管理员权限
+ """
+ if "is_admin" in self._tool_context:
+ return bool(self._tool_context.get("is_admin"))
+ if not self.has_message_context:
+ return True
+ return self.channel == NotificationChannel.Web.value and self.source in {
+ "openai",
+ "openai.responses",
+ "anthropic",
+ }
+
+ def _build_user_permissions_prompt(self) -> str:
+ """
+ 为非管理员直接网页会话构造面向模型的真实权限说明。
+
+ :return: 权限边界文本;管理员或非网页会话返回空字符串
+ """
+ if not self._is_direct_web_session() or self.is_background:
+ return ""
+ if self._effective_is_admin():
+ return ""
+ if self._tool_context.get("web_user_active") is False:
+ return "- 当前会话账号已被停用,严禁执行任何业务或管理工具操作,请提示用户联系管理员。"
+ permissions = self._tool_context.get("web_user_permissions")
+ return describe_web_permissions(
+ is_superuser=False,
+ permissions=permissions if isinstance(permissions, dict) else None,
+ )
+
def _refresh_tool_context(self, values: Dict[str, object]) -> None:
"""
刷新本轮工具共享上下文。
@@ -1896,6 +2029,16 @@ class MoviePilotAgent:
"""
runtime_config = await self._resolve_llm_runtime_config()
scope = current_terminal_scope()
+ raw_web_permissions = self._tool_context.get("web_user_permissions")
+ web_perm_sig = (
+ web_permissions_signature(
+ self._effective_is_admin(),
+ raw_web_permissions if isinstance(raw_web_permissions, dict) else None,
+ is_active=self._tool_context.get("web_user_active") is not False,
+ )
+ if self._is_direct_web_session() and not self.is_background
+ else None
+ )
return (
scope.task_id if scope is not None and scope.kind == "scheduled" else None,
streaming,
@@ -1904,7 +2047,8 @@ class MoviePilotAgent:
self.user_id,
self.username,
self.allow_message_tools,
- bool(self._tool_context.get("is_admin")),
+ self._effective_is_admin(),
+ web_perm_sig,
self.has_message_context,
self.is_background,
get_runtime_setting("AI_AGENT_VERBOSE"),
@@ -1990,6 +2134,8 @@ class MoviePilotAgent:
"reply_mode": None,
"should_dispatch_reply": False,
"is_admin": bool(self._tool_context.get("is_admin")),
+ "web_user_active": self._tool_context.get("web_user_active"),
+ "web_user_permissions": self._tool_context.get("web_user_permissions"),
"execution_user_id": self.execution_user_id,
"execution_user_identity": self.execution_user_identity,
"authorization_id": self._tool_context.get("authorization_id"),
@@ -2033,6 +2179,8 @@ class MoviePilotAgent:
"reply_mode": None,
"should_dispatch_reply": False,
"is_admin": bool(self._tool_context.get("is_admin")),
+ "web_user_active": self._tool_context.get("web_user_active"),
+ "web_user_permissions": self._tool_context.get("web_user_permissions"),
"execution_user_id": self.execution_user_id,
"execution_user_identity": self.execution_user_identity,
"authorization_id": self._tool_context.get("authorization_id"),
@@ -2105,19 +2253,35 @@ class MoviePilotAgent:
api_protocol=runtime_config.get("api_protocol"),
base_url=runtime_config.get("base_url"),
)
+ is_admin = self._effective_is_admin()
base_tool_catalog, base_subagent_catalog = self._initialize_local_tool_catalogs()
mcp_specs = await agent_mcp_manager.list_enabled_tool_specs()
- local_tools = self._filter_local_web_search_tools(
+ raw_local_tools = self._filter_local_web_search_tools(
base_tool_catalog.tools,
enabled=web_search_resolution.use_local_web_search,
)
- mcp_tools = await self._initialize_mcp_tools(specs=mcp_specs)
- tools = [*local_tools, *mcp_tools]
- local_subagent_tools = self._filter_local_web_search_tools(
+ raw_mcp_tools = await self._initialize_mcp_tools(specs=mcp_specs)
+ raw_local_subagent_tools = self._filter_local_web_search_tools(
base_subagent_catalog.tools,
enabled=web_search_resolution.use_local_web_search,
)
- subagent_mcp_tools = await self._initialize_subagent_mcp_tools(specs=mcp_specs)
+ raw_subagent_mcp_tools = await self._initialize_subagent_mcp_tools(specs=mcp_specs)
+ # 先对全量已装配工具校验命名唯一性,避免非管理员过滤掩盖配置或插件同名冲突。
+ ToolCatalogSnapshot.from_tools(
+ [*raw_local_subagent_tools, *raw_subagent_mcp_tools],
+ plugin_revision=base_subagent_catalog.plugin_revision,
+ factory_revision=base_subagent_catalog.factory_revision,
+ ).require_unique()
+ ToolCatalogSnapshot.from_tools(
+ [*raw_local_tools, *raw_mcp_tools],
+ plugin_revision=base_tool_catalog.plugin_revision,
+ factory_revision=base_tool_catalog.factory_revision,
+ ).require_unique()
+ local_tools = self._filter_tools_for_principal(raw_local_tools, is_admin=is_admin)
+ mcp_tools = self._filter_tools_for_principal(raw_mcp_tools, is_admin=is_admin)
+ tools = [*local_tools, *mcp_tools]
+ local_subagent_tools = self._filter_tools_for_principal(raw_local_subagent_tools, is_admin=is_admin)
+ subagent_mcp_tools = self._filter_tools_for_principal(raw_subagent_mcp_tools, is_admin=is_admin)
subagent_catalog = ToolCatalogSnapshot.from_tools(
[*local_subagent_tools, *subagent_mcp_tools],
plugin_revision=base_subagent_catalog.plugin_revision,
@@ -2125,7 +2289,11 @@ class MoviePilotAgent:
).require_unique()
subagent_tools = [*local_subagent_tools, *subagent_mcp_tools]
# 系统提示词
- system_prompt = prompt_manager.get_agent_prompt(channel=self.channel)
+ system_prompt = prompt_manager.get_agent_prompt(
+ channel=self.channel,
+ is_admin=is_admin,
+ user_permissions_prompt=self._build_user_permissions_prompt(),
+ )
if any(tool.name == "knowledge_search" for tool in local_tools):
system_prompt = f"{system_prompt}\n\n{_private_knowledge_guidance()}"
@@ -2231,9 +2399,11 @@ class MoviePilotAgent:
output_middleware,
*invocation_middlewares,
skills_middleware,
- # Jobs 任务管理
- JobsMiddleware(
- sources=[str(agent_runtime_manager.jobs_dir)],
+ # Jobs 任务管理仅对管理员暴露,避免向普通用户注入后台管理员任务定义。
+ *(
+ [JobsMiddleware(sources=[str(agent_runtime_manager.jobs_dir)])]
+ if is_admin
+ else []
),
# 运行时人格与核心规则
RuntimeConfigMiddleware(),
diff --git a/app/agent/policy/contracts.py b/app/agent/policy/contracts.py
index fcf1028f6..4fb35fc63 100644
--- a/app/agent/policy/contracts.py
+++ b/app/agent/policy/contracts.py
@@ -357,7 +357,7 @@ class ToolPolicyContext:
"""
根据当前宿主上下文生成本次调用主体。
"""
- if self.principal_type in {PrincipalType.BACKGROUND, PrincipalType.SUBAGENT}:
+ if self.principal_type is PrincipalType.BACKGROUND:
default_role = PrincipalRole.SYSTEM_INTERNAL
else:
default_role = PrincipalRole.USER
diff --git a/app/agent/prompt/__init__.py b/app/agent/prompt/__init__.py
index d5cd6482f..60d894804 100644
--- a/app/agent/prompt/__init__.py
+++ b/app/agent/prompt/__init__.py
@@ -158,10 +158,19 @@ class PromptManager:
logger.error(f"加载提示词失败: {prompt_name}, 错误: {e}")
raise
- def get_agent_prompt(self, channel: Optional[str] = None) -> str:
+ def get_agent_prompt(
+ self,
+ channel: Optional[str] = None,
+ *,
+ is_admin: bool = True,
+ user_permissions_prompt: str = "",
+ ) -> str:
"""
- 获取智能体提示词
+ 获取智能体提示词。
+
:param channel: 消息渠道(Telegram、微信、Slack等)
+ :param is_admin: 当前会话主体是否拥有系统管理员上下文
+ :param user_permissions_prompt: 非管理员用户的权限边界说明
:return: 提示词内容
"""
# 基础提示词包含领域任务、代码工作流、授权边界和渠道能力约束。
@@ -183,7 +192,7 @@ class PromptManager:
rich_message_spec = self._generate_rich_message_instructions(msg_channel)
# MoviePilot系统信息
- moviepilot_info = self._get_moviepilot_info()
+ moviepilot_info = self._get_moviepilot_info(is_admin=is_admin)
voice_reply_spec = self._generate_voice_reply_instructions()
# 始终替换占位符,避免后续 .format() 时因残留花括号报 KeyError
@@ -195,6 +204,10 @@ class PromptManager:
rich_message_spec=rich_message_spec,
)
+ normalized_permissions = str(user_permissions_prompt or "").strip()
+ if normalized_permissions:
+ base_prompt = f"{base_prompt}\n\n\n{normalized_permissions}\n"
+
base_prompt = f"{base_prompt}\n\n{self._get_output_language_instruction()}"
return base_prompt
@@ -322,12 +335,22 @@ class PromptManager:
sections.append(self._format_numbered_rules("IMPORTANT", rules))
return "\n\n".join(section for section in sections if section).strip()
- def _get_moviepilot_info(self) -> str:
+ def _get_moviepilot_info(self, *, is_admin: bool = True) -> str:
"""
获取需要常驻注入的最小 MoviePilot 运行信息。
+
+ :param is_admin: 当前会话主体是否拥有系统管理员权限;普通用户不注入宿主机路径与命令环境
+ :return: 格式化后的运行信息文本
"""
# 保留日期用于提供“今天是哪天”的稳定上下文,但不再注入秒级时间,
# 避免每次请求都生成不同的 system prompt,影响 provider 侧 cache 命中率。
+ if not is_admin:
+ return "\n".join(
+ [
+ f"- 当前日期: {strftime('%Y-%m-%d')}",
+ "- 当前为非管理员会话:仅可调用当前已开放的业务工具,无法执行宿主机命令、读写宿主机文件、修改系统配置或调用管理员/插件管理能力。",
+ ]
+ )
info_lines = [
f"- 当前日期: {strftime('%Y-%m-%d')}",
f"- 运行环境: {SystemUtils.platform} {'docker' if SystemUtils.is_docker() else ''}",
diff --git a/app/agent/tools/base.py b/app/agent/tools/base.py
index d5e883b99..c75a24a79 100644
--- a/app/agent/tools/base.py
+++ b/app/agent/tools/base.py
@@ -874,6 +874,30 @@ class MoviePilotTool(BaseTool, metaclass=ABCMeta):
resolved_roots.append(resolved_root)
return resolved_roots
+ def _get_non_admin_upload_roots(self) -> list[Path]:
+ """
+ 获取当前会话普通用户可只读访问的附件上传目录。
+
+ :return: 当前会话归属的临时附件目录列表
+ """
+ temp_path = get_runtime_setting("TEMP_PATH")
+ raw_session_id = str(self._session_id or "").strip()
+ if not temp_path or not raw_session_id:
+ return []
+ if "/" in raw_session_id or "\\" in raw_session_id or ".." in raw_session_id:
+ return []
+ upload_base = self._resolve_local_path(str(Path(temp_path) / "agent_uploads"))
+ candidates = {raw_session_id.replace(":", "_"), raw_session_id}
+ roots: list[Path] = []
+ for candidate in candidates:
+ if not candidate or candidate in {".", ".."}:
+ continue
+ resolved_dir = self._resolve_local_path(str(upload_base / candidate))
+ if self._is_path_relative_to(resolved_dir, upload_base) and resolved_dir != upload_base:
+ if resolved_dir not in roots:
+ roots.append(resolved_dir)
+ return roots
+
async def _check_local_file_access(
self, path: str, operation: str = "访问"
) -> tuple[Optional[Path], Optional[str]]:
@@ -891,6 +915,12 @@ class MoviePilotTool(BaseTool, metaclass=ABCMeta):
if await self.is_admin_user():
return resolved_path, None
+ if operation == "读取" and any(
+ self._is_path_relative_to(resolved_path, upload_root)
+ for upload_root in self._get_non_admin_upload_roots()
+ ):
+ return resolved_path, None
+
allowed_roots = self._get_non_admin_local_file_roots()
if not any(
self._is_path_relative_to(resolved_path, root)
@@ -903,6 +933,9 @@ class MoviePilotTool(BaseTool, metaclass=ABCMeta):
)
agent_root = allowed_roots[0]
+ if self._is_path_relative_to(resolved_path, agent_root / "jobs"):
+ return resolved_path, "抱歉,Agent 后台任务配置仅允许系统管理员访问。"
+
memory_root = agent_root / "memory"
runtime_root = agent_root / "runtime"
for protected in (runtime_root / 'learning' / 'users', runtime_root / 'history' / 'users', runtime_root / 'code' / 'users'):
@@ -920,6 +953,11 @@ class MoviePilotTool(BaseTool, metaclass=ABCMeta):
return resolved_path, '抱歉,公共技能只有系统管理员才能修改;个人学习请使用 skill_manage。'
if not self._is_path_relative_to(resolved_path, memory_root):
+ if operation != "读取":
+ return (
+ resolved_path,
+ "抱歉,普通用户只能修改自己的用户级记忆,不能修改 Agent 公共或系统文件。",
+ )
return resolved_path, None
user_memory_root = memory_root / "users"
diff --git a/app/agent/tools/impl/api.py b/app/agent/tools/impl/api.py
index b3920a558..e04282e49 100644
--- a/app/agent/tools/impl/api.py
+++ b/app/agent/tools/impl/api.py
@@ -24,6 +24,7 @@ from app.agent.policy.sanitizer import contains_redacted_placeholder, summarize_
from app.agent.tools.base import MoviePilotTool
from app.agent.tools.result import inspect_tool_result
from app.agent.tools.tags import ToolTag
+from app.domain.authorization import authorize_web_operation, normalize_web_permissions
from app.schemas.common import JsonData
from app.schemas.types import NotificationChannel
@@ -144,6 +145,7 @@ class MoviePilotApiTool(MoviePilotTool):
)
_executor: Optional[MoviePilotApiExecutor] = PrivateAttr(default=None)
+ _resolved_web_permissions: Optional[dict[str, Any]] = PrivateAttr(default=None)
def __init__(
self,
@@ -158,6 +160,54 @@ class MoviePilotApiTool(MoviePilotTool):
"""
super().__init__(session_id=session_id, user_id=user_id, **kwargs)
self._executor = executor
+ self._resolved_web_permissions = None
+
+ def _is_direct_web_session(self) -> bool:
+ """
+ 判断当前工具调用是否来自直接登录用户的网页或 WebAgent 会话。
+
+ :return: 排除 OpenAI/Anthropic/API 集成通道后的直接网页会话返回 True
+ """
+ return (
+ self._channel in {NotificationChannel.Web.value, NotificationChannel.WebAgent.value}
+ and self._source not in {"api", "openai", "openai.responses", "anthropic"}
+ )
+
+ def _get_resolved_web_permissions(self) -> dict[str, Any]:
+ """
+ 读取当前直接网页会话的实时归一化权限。
+
+ :return: 归一化后的网页用户权限字典
+ """
+ if self._resolved_web_permissions is not None:
+ return self._resolved_web_permissions
+ context_permissions = self._agent_context.get("web_user_permissions")
+ if isinstance(context_permissions, dict):
+ return normalize_web_permissions(context_permissions)
+ return normalize_web_permissions(None)
+
+ @staticmethod
+ def _extract_request_media_type(
+ *,
+ query: Optional[Dict[str, Any]],
+ body: Any,
+ ) -> Optional[str]:
+ """
+ 从订阅请求参数中提取媒体类型,用于细分订阅功能级权限校验。
+
+ :param query: 查询参数字典
+ :param body: 请求体对象
+ :return: 媒体类型字符串;未提供时返回 None
+ """
+ candidates: list[Any] = []
+ if isinstance(body, dict):
+ candidates.extend((body.get("type"), body.get("mtype")))
+ if isinstance(query, dict):
+ candidates.extend((query.get("type_name"), query.get("mtype"), query.get("type")))
+ for candidate in candidates:
+ if isinstance(candidate, str) and candidate.strip():
+ return candidate.strip()
+ return None
def get_tool_message(self, **kwargs: Any) -> Optional[str]:
"""
@@ -310,6 +360,7 @@ class MoviePilotApiTool(MoviePilotTool):
except AgentIdentityError as error:
self._record_identity_error(str(error))
raise ApiExecutionError(str(error)) from error
+ self._resolved_web_permissions = normalize_web_permissions(getattr(execution_user, "permissions", None))
return str(execution_user.id), execution_user.name, bool(execution_user.is_superuser)
is_authenticated_integration = self._source == "api" or (
self._channel == NotificationChannel.Web.value
@@ -346,7 +397,15 @@ class MoviePilotApiTool(MoviePilotTool):
if user is None:
raise ApiExecutionError(self._identity_unavailable_message())
if not user.is_active:
+ if is_direct_user_channel:
+ self._agent_context["web_user_active"] = False
raise ApiExecutionError("当前 MoviePilot 用户已停用,请联系管理员启用该用户后重试。重新绑定不能解除停用。")
+ if is_direct_user_channel:
+ normalized_permissions = normalize_web_permissions(getattr(user, "permissions", None))
+ self._resolved_web_permissions = normalized_permissions
+ self._agent_context["web_user_active"] = True
+ self._agent_context["web_user_permissions"] = normalized_permissions
+ self._agent_context["is_admin"] = bool(user.is_superuser)
return str(user.id), user.name, bool(user.is_superuser)
def _identity_unavailable_message(self) -> str:
@@ -393,11 +452,18 @@ class MoviePilotApiTool(MoviePilotTool):
public_read_only: bool = False,
) -> tuple[MoviePilotApiExecutor, bool]:
"""
- 解析执行身份;公共资料使用只能执行白名单读取的宿主认证通道。
+ 解析执行身份;非网页渠道的公共资料使用宿主只读通道,直接网页会话始终绑定真实登录用户。
+
+ :param require_system_admin: 当前操作在非网页渠道下是否要求系统管理员
+ :param public_read_only: 当前操作是否属于免绑定公共只读资料
+ :return: ``(API 执行器, 是否超级管理员)`` 二元组
"""
+ self._resolved_web_permissions = None
if self._executor is not None:
return self._executor, await self.is_admin_user()
- if public_read_only and not isinstance(self._agent_context.get("execution_user_id"), int):
+ is_direct_web = self._is_direct_web_session()
+ effective_public_read_only = public_read_only and not is_direct_web
+ if effective_public_read_only and not isinstance(self._agent_context.get("execution_user_id"), int):
user_id, username, is_admin = await self._resolve_superuser_integration_identity()
else:
user_id, username, is_admin = await self._resolve_api_identity(
@@ -412,12 +478,14 @@ class MoviePilotApiTool(MoviePilotTool):
session_id=self._session_id,
channel=self._channel,
source=self._source,
- public_read_only=public_read_only,
+ public_read_only=effective_public_read_only,
# 公共资料使用宿主身份只读查询,不绑定渠道发起人
channel_user_id=(
- str(self._user_id) if self._channel and self._user_id and not public_read_only else None
+ str(self._user_id)
+ if self._channel and self._user_id and not effective_public_read_only
+ else None
),
- authorization_id=str(self._agent_context.get("authorization_id") or "") or None,
+ authorization_id=str(self._agent_context.get("authorization_id") or "") or None,
)
),
is_admin,
@@ -485,7 +553,34 @@ class MoviePilotApiTool(MoviePilotTool):
require_system_admin=requires_system_admin,
public_read_only=operation_id in API_UNBOUND_READ_OPERATIONS,
)
- if requires_system_admin and not is_admin:
+ if self._is_direct_web_session():
+ if self._agent_context.get("web_user_active") is False:
+ self._record_identity_error("当前 MoviePilot 用户已停用,请联系管理员启用该用户后重试。")
+ return json.dumps(
+ {
+ "success": False,
+ "error": "permission_denied",
+ "message": "当前 MoviePilot 用户已停用,请联系管理员启用该用户后重试。",
+ },
+ ensure_ascii=False,
+ )
+ allowed, denial_reason = authorize_web_operation(
+ is_superuser=is_admin,
+ permissions=self._get_resolved_web_permissions(),
+ operation_id=operation_id,
+ media_type=self._extract_request_media_type(query=query, body=body),
+ )
+ if not allowed:
+ self._record_identity_error(denial_reason)
+ return json.dumps(
+ {
+ "success": False,
+ "error": "permission_denied",
+ "message": denial_reason,
+ },
+ ensure_ascii=False,
+ )
+ elif requires_system_admin and not is_admin:
self._record_identity_error("任务执行账号不具备此操作需要的系统管理员权限。")
return json.dumps(
{
diff --git a/app/agent/web.py b/app/agent/web.py
index d1bb8e9c3..eebc4b05f 100644
--- a/app/agent/web.py
+++ b/app/agent/web.py
@@ -8,6 +8,7 @@ from threading import Lock
from typing import Any, Awaitable, Callable, Optional
from app.agent.loader import get_moviepilot_agent_type
+from app.agent.tools.base import run_agent_blocking
from app.application.security.user import get_configured_user_id_lookup
from app.runtime.log import logger
from app.schemas.message import Message
@@ -364,24 +365,40 @@ class _WebAgentMoviePilotAgentMixin:
if isinstance(self.stream_handler, _WebAgentStreamingHandlerMixin):
self.stream_handler.set_tool_event_callback(tool_event_callback)
- async def _is_system_admin_context(self) -> bool:
+ async def _resolve_web_user(self) -> Any:
"""
- Web Agent 根据当前登录用户 ID 判断工具管理员上下文。
+ 实时查询当前 Web Agent 登录用户快照,不阻塞事件循环。
+
+ :return: 当前登录用户对象;未找到或标识非法时返回 None
"""
if not self.user_id:
- return False
+ return None
try:
- user = get_configured_user_id_lookup()(int(self.user_id))
+ parsed_user_id = int(self.user_id)
except (TypeError, ValueError):
- return False
+ return None
+ try:
+ lookup = get_configured_user_id_lookup()
+ return await run_agent_blocking("db", lookup, parsed_user_id)
except Exception as e:
- logger.error(f"检查 Web Agent 用户管理员身份失败: {e}")
- return False
- return bool(user and user.is_superuser)
+ logger.error(f"检查 Web Agent 登录用户失败: {e}")
+ return None
+
+ async def _is_system_admin_context(self) -> bool:
+ """
+ Web Agent 根据当前激活登录用户 ID 判断工具管理员上下文。
+
+ :return: 当前登录用户处于激活状态且为超级管理员时返回 True
+ """
+ user = await self._resolve_web_user()
+ return bool(user and getattr(user, "is_active", True) is not False and user.is_superuser)
async def _build_tool_context(self, should_dispatch_reply: bool) -> dict[str, object]:
"""
向工具上下文注入 Web SSE 通知回调。
+
+ :param should_dispatch_reply: 本轮是否需要向渠道派发回复
+ :return: 包含回调和实时权限状态的工具上下文
"""
# 该方法由运行时组合进 MRO 的 MoviePilotAgent 提供。
context = await super()._build_tool_context( # type: ignore[misc]
diff --git a/app/api/dependencies/auth.py b/app/api/dependencies/auth.py
index f27b70c44..5b1fe245d 100644
--- a/app/api/dependencies/auth.py
+++ b/app/api/dependencies/auth.py
@@ -23,6 +23,7 @@ from app.application.security.user import (
UserService,
)
from app.application.security.userconfig import get_configured_user_configuration
+from app.domain.authorization import has_web_permission
from app.schemas.token import TokenPayload as _SchemaTokenPayload
from app.startup.composition.context import HostRuntime
@@ -170,11 +171,21 @@ def _ensure_manage_user(current_user: Any) -> Any:
def get_current_download_viewer(current_user: Any = Depends(get_current_active_user)) -> Any:
"""
- 渠道成员仅查看自己的下载;普通网页入口继续要求全局管理权限。
+ 允许管理员、下载管理用户查看全局下载;渠道成员及具备搜索/订阅权限的普通网页用户仅可查看本人下载。
+
+ :param current_user: 当前已认证激活用户
+ :return: 通过校验的当前用户
"""
if getattr(current_user, "authorization_id", None) and current_user.permissions.get("download") is True:
return current_user
- return _ensure_manage_user(current_user)
+ permissions = getattr(current_user, "permissions", None)
+ if current_user.is_superuser or has_web_permission(False, permissions, "manage", "manage.downloading"):
+ return current_user
+ if has_web_permission(False, permissions, "search", "search.resource") or has_web_permission(
+ False, permissions, "subscribe"
+ ):
+ return current_user
+ raise HTTPException(status_code=403, detail="用户权限不足")
def get_current_active_manage_user(
diff --git a/app/api/endpoints/download.py b/app/api/endpoints/download.py
index 10f61cfb9..7563314ed 100644
--- a/app/api/endpoints/download.py
+++ b/app/api/endpoints/download.py
@@ -31,6 +31,7 @@ from app.application.site.query import (
)
from app.chain.download import DownloadChain
from app.chain.media import MediaChain
+from app.domain.authorization import has_web_permission
from app.domain.context import Context, MediaInfo, MusicInfo, SubtitleInfo, TorrentInfo
from app.domain.media import is_music_media_source, normalize_music_type
from app.domain.meta.metabase import MetaBase
@@ -227,10 +228,17 @@ def _resolve_add_media(
@router.get("/", summary="正在下载", response_model=List[_SchemaDownloaderTorrent])
def current(name: Optional[str] = None, _: ApiPrincipal = Depends(get_current_download_viewer), page: CompatiblePageParam = None, count: CompatibleCountParam = None) -> Any:
"""
- 管理员查询全局下载任务,获授权渠道成员仅查询自己发起的任务。
+ 管理员及下载管理权限用户查询全局下载任务,其余已授权用户仅查询自己发起的任务。
"""
tasks = DownloadChain().downloading(name)
- if getattr(_, "authorization_id", None) and not _.is_superuser:
+ can_view_all = bool(
+ _.is_superuser
+ or (
+ not getattr(_, "authorization_id", None)
+ and has_web_permission(False, getattr(_, "permissions", None), "manage", "manage.downloading")
+ )
+ )
+ if not can_view_all:
return [task for task in tasks if task.username == _.name]
return tasks
diff --git a/app/api/endpoints/history.py b/app/api/endpoints/history.py
index 631a5aaf0..64d9a0756 100644
--- a/app/api/endpoints/history.py
+++ b/app/api/endpoints/history.py
@@ -292,6 +292,33 @@ async def download_history(
if response is not None:
response.headers[COLLECTION_TOTAL_HEADER] = str(await query.count_download(username=username))
return results
+ if isinstance(_, _SchemaTokenPayload) and not _.super_user:
+ from app.application.security.user import get_configured_user_id_lookup
+ from app.domain.authorization import has_web_permission
+ from app.runtime.execution import run_in_threadpool
+
+ web_username: Optional[str] = None
+ if _.sub is not None:
+ lookup = get_configured_user_id_lookup()
+ web_user = await run_in_threadpool(lookup, int(_.sub))
+ if web_user is None or not web_user.is_active:
+ raise HTTPException(status_code=401, detail="用户未激活")
+ if web_user.is_superuser or has_web_permission(False, web_user.permissions, "manage", "manage.downloading"):
+ web_username = None
+ elif has_web_permission(False, web_user.permissions, "search", "search.resource") or has_web_permission(
+ False, web_user.permissions, "subscribe"
+ ):
+ web_username = web_user.name
+ else:
+ raise HTTPException(status_code=403, detail="用户权限不足")
+ elif _.username:
+ web_username = _.username
+ else:
+ raise HTTPException(status_code=403, detail="用户权限不足")
+ results = await query.list_download(page=page, count=count, username=web_username)
+ if response is not None:
+ response.headers[COLLECTION_TOTAL_HEADER] = str(await query.count_download(username=web_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/message.py b/app/api/endpoints/message.py
index 739a08290..968e510cb 100644
--- a/app/api/endpoints/message.py
+++ b/app/api/endpoints/message.py
@@ -15,7 +15,7 @@ from app.adapters.external.wechat import WXBizMsgCrypt
from app.adapters.web.security.access import verify_apitoken, verify_token
from app.api.context import get_background_task_registry, resolve_background_task_registry
from app.api.dependencies.agent import get_message_query_service
-from app.api.dependencies.auth import get_current_active_superuser
+from app.api.dependencies.auth import get_current_active_superuser, get_current_active_user
from app.api.principal import ApiPrincipal
from app.api.response import ResponseAPIRouter
from app.application.configuration import (
@@ -178,10 +178,10 @@ async def user_message(
async def web_message(
request: Request,
text: Optional[str] = None,
- current_user: ApiPrincipal = Depends(get_current_active_superuser),
+ current_user: ApiPrincipal = Depends(get_current_active_user),
) -> _SchemaResponse[None]:
"""
- WEB消息响应
+ 接收并处理当前登录用户的 WEB 消息,按真实登录用户身份绑定权限。
"""
images = None
content_type = request.headers.get("content-type") or ""
@@ -205,10 +205,11 @@ async def web_message(
MessageChain().handle_message(
channel=NotificationChannel.Web,
source=current_user.name,
- userid=current_user.name,
+ userid=str(current_user.id),
username=current_user.name,
text=text or "",
images=images,
+ is_channel_admin=bool(current_user.is_superuser),
)
return _SchemaResponse(success=True)
diff --git a/app/chain/message.py b/app/chain/message.py
index 0b9acb900..5c2fd0bf3 100644
--- a/app/chain/message.py
+++ b/app/chain/message.py
@@ -408,7 +408,12 @@ class MessageChain(ChainBase):
is_channel_admin=is_channel_admin,
)
- if is_special_plugin_text:
+ is_non_admin_web = (
+ channel in {NotificationChannel.Web, NotificationChannel.WebAgent}
+ and is_channel_admin is False
+ )
+
+ if is_special_plugin_text and not is_non_admin_web:
# 插件验证码等专用输入不进入 Agent、普通历史或传统命令路由。
self._dispatch_plugin_text(interaction_context, text, reply_to_message_id)
return
@@ -420,7 +425,7 @@ class MessageChain(ChainBase):
processing_finish_deferred = member_result
return
- if (not channel_managed or is_channel_admin) and self._plugin_input_interaction_handler().handle_text(
+ if (not channel_managed or is_channel_admin) and not is_non_admin_web and self._plugin_input_interaction_handler().handle_text(
context=interaction_context,
text=text,
reply_to_message_id=reply_to_message_id,
@@ -726,7 +731,12 @@ class MessageChain(ChainBase):
)
return False
- if self._plugin_input_interaction_handler().handle_text(
+ is_non_admin_web = (
+ channel in {NotificationChannel.Web, NotificationChannel.WebAgent}
+ and is_channel_admin is False
+ )
+
+ if not is_non_admin_web and self._plugin_input_interaction_handler().handle_text(
context=context,
text=text,
reply_to_message_id=reply_to_message_id,
@@ -754,6 +764,18 @@ class MessageChain(ChainBase):
return False
if text.startswith("/") and not self._has_ai_prefix(text) and not is_agent_learning_command(text):
+ if is_non_admin_web:
+ self.post_message(
+ Message(
+ channel=channel,
+ source=source,
+ userid=userid,
+ username=username,
+ title="只有管理员才有权限执行此命令",
+ save_history=False,
+ )
+ )
+ return False
self.eventmanager.send_event(
EventType.CommandExcute,
{
diff --git a/app/domain/authorization.py b/app/domain/authorization.py
index 93debc33f..d098f5a49 100644
--- a/app/domain/authorization.py
+++ b/app/domain/authorization.py
@@ -1,9 +1,13 @@
"""
-通知渠道授权的旧配置映射与权限范围。
+通知渠道授权与网页用户权限的领域规则与能力映射。
-旧投递接收人只在升级时用于保留已有管理员身份,运行时不再据此授权。
+旧投递接收人只在升级时用于保留已有管理员身份,运行时不再据此授权;
+网页用户实时权限由超级管理员标识与权限分类/功能开关共同决定。
"""
+from collections.abc import Mapping
+from typing import Any
+
from app.schemas.types import NotificationChannel
# 类型、渠道、旧普通用户键、旧管理员键和升级时保留的主用户键。
@@ -93,3 +97,390 @@ CHANNEL_PUBLIC_OPERATIONS = frozenset(
"plugin.statistics",
}
)
+
+# 网页普通用户支持的顶层权限分类;admin 标记不能授予超级管理员身份。
+WEB_PERMISSION_CATEGORIES = ("discovery", "search", "subscribe", "manage")
+
+# 网页权限分类的中文名称,用于向模型说明当前用户具备的真实边界。
+WEB_PERMISSION_CATEGORY_LABELS = {
+ "discovery": "发现(推荐/探索)",
+ "search": "资源搜索",
+ "subscribe": "订阅管理",
+ "manage": "系统管理(站点/下载/历史/文件/工作流等受托管理项)",
+}
+
+# 网页功能级权限键的中文名称,与前端权限配置保持一致。
+WEB_PERMISSION_FEATURE_LABELS = {
+ "discovery.recommend": "推荐",
+ "discovery.explore": "探索",
+ "search.resource": "资源搜索",
+ "subscribe.movie": "电影订阅",
+ "subscribe.tv": "电视剧订阅",
+ "subscribe.music": "音乐订阅",
+ "subscribe.calendar": "订阅日历",
+ "subscribe.share": "订阅分享",
+ "manage.workflow": "工作流",
+ "manage.downloading": "正在下载",
+ "manage.history": "历史记录",
+ "manage.filemanager": "文件管理",
+ "manage.site": "站点管理",
+}
+
+# 订阅媒体类型与功能级权限键的映射。
+_SUBSCRIBE_MEDIA_TYPE_FEATURES = {
+ "movie": "subscribe.movie",
+ "电影": "subscribe.movie",
+ "tv": "subscribe.tv",
+ "电视剧": "subscribe.tv",
+ "music": "subscribe.music",
+ "音乐": "subscribe.music",
+}
+
+# 网页登录用户调用白名单业务 API 的最小权限要求。
+# 映射值为满足任一 (category, feature) 条件即放行的元组;空元组表示任意激活登录用户可调用;
+# 未列入此表的操作一律仅允许超级管理员执行。
+WebPermissionRequirement = tuple[str, str | None]
+WEB_OPERATION_REQUIREMENTS: dict[str, tuple[WebPermissionRequirement, ...]] = {
+ # 基础登录配置
+ "config.user.get": (),
+ "config.public.get": (),
+ # 发现与探索
+ "recommendation.list": (("discovery", "discovery.recommend"),),
+ "music.explore": (("discovery", "discovery.explore"),),
+ "library.latest": (("discovery", None),),
+ # 媒体资料查询(发现、搜索、订阅流程均依赖基础识别与详情)
+ "media.search": (("discovery", None), ("search", "search.resource"), ("subscribe", None)),
+ "media.person.search": (("discovery", None), ("search", "search.resource"), ("subscribe", None)),
+ "media.person.credits": (("discovery", None), ("search", "search.resource"), ("subscribe", None)),
+ "media.recognize": (("discovery", None), ("search", "search.resource"), ("subscribe", None)),
+ "media.recognize_file": (
+ ("discovery", None),
+ ("search", "search.resource"),
+ ("subscribe", None),
+ ("manage", "manage.filemanager"),
+ ),
+ "media.episode_schedule": (
+ ("discovery", None),
+ ("subscribe", "subscribe.calendar"),
+ ("subscribe", None),
+ ),
+ "media.detail": (("discovery", None), ("search", "search.resource"), ("subscribe", None)),
+ "media.sources": (("discovery", None), ("search", "search.resource"), ("subscribe", None)),
+ "media.episode_groups": (("discovery", None), ("search", "search.resource"), ("subscribe", None)),
+ "media.episode_group.seasons": (
+ ("discovery", None),
+ ("search", "search.resource"),
+ ("subscribe", None),
+ ),
+ "media.seasons": (("discovery", None), ("search", "search.resource"), ("subscribe", None)),
+ "library.exists": (("discovery", None), ("search", "search.resource"), ("subscribe", None)),
+ "music.recognize": (("discovery", None), ("search", "search.resource"), ("subscribe", None)),
+ "music.album.get": (("discovery", None), ("search", "search.resource"), ("subscribe", None)),
+ "music.album.related": (("discovery", None), ("search", "search.resource"), ("subscribe", None)),
+ "music.artist.get": (("discovery", None), ("search", "search.resource"), ("subscribe", None)),
+ "music.artist.albums": (("discovery", None), ("search", "search.resource"), ("subscribe", None)),
+ "music.artist.related": (("discovery", None), ("search", "search.resource"), ("subscribe", None)),
+ # 搜索、下载与规则读取
+ "search.torrents": (("search", "search.resource"),),
+ "search.results": (("search", "search.resource"),),
+ "search.title": (("search", "search.resource"),),
+ "search.recommend": (("discovery", "discovery.recommend"), ("search", "search.resource")),
+ "subtitle.search.title": (("search", "search.resource"),),
+ "subtitle.search.media": (("search", "search.resource"),),
+ "download.add": (("search", "search.resource"), ("subscribe", None)),
+ "download.artist_collection": (("search", "search.resource"), ("subscribe", "subscribe.music")),
+ "download.clients": (
+ ("search", "search.resource"),
+ ("subscribe", None),
+ ("manage", "manage.downloading"),
+ ),
+ "download.paths": (
+ ("search", "search.resource"),
+ ("subscribe", None),
+ ("manage", "manage.downloading"),
+ ),
+ "download.tasks.active": (
+ ("search", "search.resource"),
+ ("subscribe", None),
+ ("manage", "manage.downloading"),
+ ),
+ "download.history.list": (
+ ("search", "search.resource"),
+ ("subscribe", None),
+ ("manage", "manage.downloading"),
+ ),
+ "filter.builtin": (("search", "search.resource"), ("subscribe", None)),
+ "filter.custom": (("search", "search.resource"), ("subscribe", None)),
+ "filter.groups": (("search", "search.resource"), ("subscribe", None)),
+ "site.list": (("search", "search.resource"), ("subscribe", None), ("manage", "manage.site")),
+ # 订阅
+ "subscription.add": (("subscribe", None),),
+ "subscription.update": (("subscribe", None),),
+ "subscription.search": (("subscribe", None),),
+ "subscription.search_all": (("subscribe", None),),
+ "subscription.list": (("subscribe", None),),
+ "subscription.get": (("subscribe", None),),
+ "subscription.find": (("subscribe", None),),
+ "subscription.user.list": (("subscribe", None),),
+ "subscription.history": (("subscribe", None),),
+ "subscription.history.delete": (("subscribe", None),),
+ "subscription.delete": (("subscribe", None),),
+ "subscription.delete_by_media": (("subscribe", None),),
+ "subscription.status.update": (("subscribe", None),),
+ "subscription.reset": (("subscribe", None),),
+ "subscription.files": (("subscribe", None),),
+ "subscription.execution.list": (("subscribe", None),),
+ "subscription.execution.get": (("subscribe", None),),
+ "subscription.execution.cancel": (("subscribe", None),),
+ "subscription.shares": (("subscribe", "subscribe.share"),),
+ "subscription.popular": (("subscribe", "subscribe.share"),),
+ "subscription.share.statistics": (("subscribe", "subscribe.share"),),
+ "subscription.share": (("subscribe", "subscribe.share"),),
+ "subscription.fork": (("subscribe", "subscribe.share"),),
+ "subscription.share.delete": (("manage", None),),
+ "subscription.follow.list": (("manage", None),),
+ "subscription.follow.add": (("manage", None),),
+ "subscription.follow.delete": (("manage", None),),
+ # 受托管理:站点
+ "site.add": (("manage", "manage.site"),),
+ "site.update": (("manage", "manage.site"),),
+ "site.delete": (("manage", "manage.site"),),
+ "site.userdata": (("manage", "manage.site"),),
+ "site.userdata.refresh": (("manage", "manage.site"),),
+ "site.userdata.latest": (("manage", "manage.site"),),
+ "site.cookie.update": (("manage", "manage.site"),),
+ "site.cookie.set": (("manage", "manage.site"),),
+ "site.priorities.update": (("manage", "manage.site"),),
+ "site.category": (("manage", "manage.site"),),
+ "site.resource": (("manage", "manage.site"),),
+ "site.searchable": (("manage", "manage.site"),),
+ "site.rss": (("manage", "manage.site"),),
+ "site.test": (("manage", "manage.site"),),
+ "site.statistics": (("manage", "manage.site"),),
+ "site.statistic": (("manage", "manage.site"),),
+ # 受托管理:下载与整理历史
+ "download.history.delete": (("manage", "manage.downloading"),),
+ "transfer.history": (("manage", "manage.history"),),
+ "transfer.history.delete": (("manage", "manage.history"),),
+ "transfer.history.redo": (("manage", "manage.history"),),
+ "transfer.history.redo_batch": (("manage", "manage.history"),),
+ "transfer.history.replan": (("manage", "manage.history"),),
+ "transfer.queue": (("manage", "manage.history"),),
+ "transfer.queue.delete": (("manage", "manage.history"),),
+ "transfer.name": (("manage", "manage.history"),),
+ "transfer.target_path": (("manage", "manage.history"),),
+ "transfer.manual_history": (("manage", "manage.history"),),
+ "transfer.episode_format.recommend": (("manage", "manage.history"),),
+ "transfer.manual_reviews": (("manage", "manage.history"),),
+ "transfer.manual_review": (("manage", "manage.history"),),
+ "transfer.manual_review.resolve": (("manage", "manage.history"),),
+ # 受托管理:文件管理与刮削
+ "storage.list": (("manage", "manage.filemanager"),),
+ "storage.settings": (("manage", "manage.filemanager"),),
+ "storage.mkdir": (("manage", "manage.filemanager"),),
+ "storage.rename": (("manage", "manage.filemanager"),),
+ "storage.delete": (("manage", "manage.filemanager"),),
+ "transfer.file": (("manage", "manage.filemanager"),),
+ "media.scrape": (("manage", "manage.filemanager"),),
+ # 受托管理:工作流
+ "workflow.list": (("manage", "manage.workflow"),),
+ "workflow.run": (("manage", "manage.workflow"),),
+ "workflow.create": (("manage", "manage.workflow"),),
+ "workflow.get": (("manage", "manage.workflow"),),
+ "workflow.update": (("manage", "manage.workflow"),),
+ "workflow.delete": (("manage", "manage.workflow"),),
+ "workflow.actions": (("manage", "manage.workflow"),),
+ "workflow.event_types": (("manage", "manage.workflow"),),
+ "workflow.plugin.actions": (("manage", "manage.workflow"),),
+ "workflow.start": (("manage", "manage.workflow"),),
+ "workflow.pause": (("manage", "manage.workflow"),),
+ "workflow.reset": (("manage", "manage.workflow"),),
+ "workflow.shares": (("manage", "manage.workflow"),),
+ "workflow.share": (("manage", "manage.workflow"),),
+ "workflow.share.delete": (("manage", "manage.workflow"),),
+ "workflow.fork": (("manage", "manage.workflow"),),
+}
+
+
+def normalize_web_permissions(permissions: Mapping[str, Any] | None) -> dict[str, Any]:
+ """
+ 归一化网页用户权限字典,保持缺失分类按拒绝处理且忽略非布尔功能开关。
+
+ :param permissions: 原始用户权限映射
+ :return: 仅包含规范分类布尔值与 features 映射的权限字典
+ """
+ source = permissions if isinstance(permissions, Mapping) else {}
+ raw_features = source.get("features")
+ features: dict[str, bool] = {}
+ if isinstance(raw_features, Mapping):
+ for key, value in raw_features.items():
+ if isinstance(key, str) and isinstance(value, bool):
+ features[key] = value
+ normalized: dict[str, Any] = {
+ category: source.get(category) is True
+ for category in WEB_PERMISSION_CATEGORIES
+ }
+ normalized["features"] = features
+ return normalized
+
+
+def web_permissions_signature(
+ is_superuser: bool,
+ permissions: Mapping[str, Any] | None,
+ *,
+ is_active: bool = True,
+) -> tuple[Any, ...]:
+ """
+ 构造用于 Agent 缓存键的确定性网页用户权限签名。
+
+ :param is_superuser: 是否为超级管理员
+ :param permissions: 网页用户权限字典
+ :param is_active: 账号是否处于激活状态
+ :return: 可哈希的权限状态元组
+ """
+ normalized = normalize_web_permissions(permissions)
+ features = tuple(sorted(normalized["features"].items()))
+ return (
+ bool(is_active),
+ bool(is_superuser),
+ *(normalized[category] for category in WEB_PERMISSION_CATEGORIES),
+ features,
+ )
+
+
+def has_web_permission(
+ is_superuser: bool,
+ permissions: Mapping[str, Any] | None,
+ category: str,
+ feature: str | None = None,
+) -> bool:
+ """
+ 判断网页用户是否拥有指定分类权限及可选功能级权限。
+
+ 超级管理员始终放行;普通用户必须具备对应分类权限,且指定功能键不能为 False
+ (未显式配置的功能键默认继承其所属分类权限,与前端和数据库约定一致)。
+
+ :param is_superuser: 是否为超级管理员
+ :param permissions: 网页用户权限字典
+ :param category: 顶层权限分类名
+ :param feature: 可选功能级权限键
+ :return: 是否允许访问
+ """
+ if is_superuser:
+ return True
+ if category not in WEB_PERMISSION_CATEGORIES:
+ return False
+ normalized = normalize_web_permissions(permissions)
+ if normalized.get(category) is not True:
+ return False
+ if feature and normalized["features"].get(feature) is False:
+ return False
+ return True
+
+
+def _resolve_subscribe_media_feature(media_type: str | None) -> str | None:
+ """
+ 将订阅请求中的媒体类型映射到对应的功能级权限键。
+
+ :param media_type: 请求中的媒体类型值
+ :return: 对应的订阅功能键;无法识别时返回 None
+ """
+ if not isinstance(media_type, str):
+ return None
+ normalized = media_type.strip().lower()
+ if not normalized:
+ return None
+ return _SUBSCRIBE_MEDIA_TYPE_FEATURES.get(normalized)
+
+
+def authorize_web_operation(
+ is_superuser: bool,
+ permissions: Mapping[str, Any] | None,
+ operation_id: str,
+ *,
+ media_type: str | None = None,
+) -> tuple[bool, str]:
+ """
+ 校验网页登录用户是否允许执行指定的白名单业务 API 操作。
+
+ :param is_superuser: 是否为超级管理员
+ :param permissions: 网页用户权限字典
+ :param operation_id: 白名单业务 API 操作 ID
+ :param media_type: 可选媒体类型,用于细分订阅功能权限
+ :return: ``(是否允许, 拒绝原因)`` 二元组
+ """
+ if is_superuser:
+ return True, ""
+
+ requirements = WEB_OPERATION_REQUIREMENTS.get(operation_id)
+ if requirements is None:
+ return False, f"权限不足:操作 {operation_id} 仅允许系统管理员执行"
+
+ if not requirements:
+ return True, ""
+
+ if operation_id in {"subscription.add", "subscription.update"}:
+ media_feature = _resolve_subscribe_media_feature(media_type)
+ if media_feature is not None:
+ if has_web_permission(False, permissions, "subscribe", media_feature):
+ return True, ""
+ label = WEB_PERMISSION_FEATURE_LABELS.get(media_feature, media_feature)
+ return False, f"权限不足:当前账号未开通「{label}」权限,无法执行操作 {operation_id}"
+
+ for category, feature in requirements:
+ if has_web_permission(False, permissions, category, feature):
+ return True, ""
+
+ labels: list[str] = []
+ for category, feature in requirements:
+ label = (
+ WEB_PERMISSION_FEATURE_LABELS.get(feature, feature)
+ if feature
+ else WEB_PERMISSION_CATEGORY_LABELS.get(category, category)
+ )
+ if label not in labels:
+ labels.append(label)
+ needed = "或".join(f"「{label}」" for label in labels)
+ return False, f"权限不足:当前账号缺少{needed}权限,无法执行操作 {operation_id}"
+
+
+def describe_web_permissions(
+ is_superuser: bool,
+ permissions: Mapping[str, Any] | None,
+) -> str:
+ """
+ 生成用于注入系统提示词的当前用户权限摘要,防止模型假定自己拥有管理员能力。
+
+ :param is_superuser: 是否为超级管理员
+ :param permissions: 网页用户权限字典
+ :return: 面向模型的中文权限边界描述;管理员返回空字符串
+ """
+ if is_superuser:
+ return ""
+
+ normalized = normalize_web_permissions(permissions)
+ features = normalized["features"]
+ granted_categories = [
+ WEB_PERMISSION_CATEGORY_LABELS[category]
+ for category in WEB_PERMISSION_CATEGORIES
+ if normalized[category] is True
+ ]
+ denied_features = [
+ WEB_PERMISSION_FEATURE_LABELS.get(key, key)
+ for key, value in sorted(features.items())
+ if value is False
+ ]
+ granted_text = "、".join(granted_categories) if granted_categories else "无业务功能权限(仅基础对话与基础配置读取)"
+ lines = [
+ "- 当前会话身份:普通网页登录用户(非系统管理员)。",
+ f"- 当前已开通权限:{granted_text}。",
+ ]
+ if denied_features:
+ lines.append(f"- 当前已关闭的子功能:{'、'.join(denied_features)}。")
+ lines.extend(
+ [
+ "- 严禁越权:无权执行系统配置修改、插件安装/配置/调用、定时任务调度、宿主机命令/代码执行、后台任务或查看他人下载与管理敏感信息。",
+ "- 若用户请求超出上述权限范围,请直接说明权限不足,并建议联系系统管理员调整账号权限。",
+ ]
+ )
+ return "\n".join(lines)
diff --git a/tests/test_web_agent_permissions.py b/tests/test_web_agent_permissions.py
new file mode 100644
index 000000000..8df887615
--- /dev/null
+++ b/tests/test_web_agent_permissions.py
@@ -0,0 +1,477 @@
+"""
+验证 Web Agent 与网页智能助手严格按当前登录用户的实时权限运行。
+"""
+
+import asyncio
+import json
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from fastapi import HTTPException
+from starlette.requests import Request
+from starlette.responses import Response
+
+import app.agent.orchestrator as orchestrator_module
+from app.agent.middleware.jobs import JobsMiddleware
+from app.agent.middleware.policy import AgentPolicyMiddleware
+from app.agent.orchestrator import MoviePilotAgent
+from app.agent.policy.contracts import (
+ AuthSource,
+ PrincipalRole,
+ PrincipalType,
+ ToolOrigin,
+ ToolPolicyContext,
+)
+from app.agent.prompt import PromptManager
+from app.agent.tools.base import MoviePilotTool
+from app.agent.tools.impl.api import MoviePilotApiTool
+from app.agent.tools.impl.read_file import ReadFileTool
+from app.agent.tools.impl.write_file import WriteFileTool
+from app.agent.web import _get_web_agent_type
+from app.api.dependencies.auth import get_current_download_viewer
+from app.api.endpoints import download as download_endpoint
+from app.api.endpoints import history as history_endpoint
+from app.api.endpoints import message as message_endpoint
+from app.chain.message import MessageChain
+from app.domain.authorization import (
+ authorize_web_operation,
+ describe_web_permissions,
+ has_web_permission,
+)
+from app.schemas.token import TokenPayload
+from app.schemas.types import NotificationChannel
+
+
+class _DummyTool(MoviePilotTool):
+ """
+ 用于验证权限过滤与策略拦截的最小测试工具。
+ """
+
+ name: str = "dummy_tool"
+ description: str = "dummy"
+
+ async def run(self, **kwargs: object) -> str:
+ """
+ 返回固定执行成功结果。
+ """
+ return "ok"
+
+
+class _DummyAdminTool(MoviePilotTool):
+ """
+ 模拟需要系统管理员权限的内置工具。
+ """
+
+ name: str = "dummy_admin_tool"
+ description: str = "admin only"
+ require_admin: bool = True
+
+ async def run(self, **kwargs: object) -> str:
+ """
+ 返回固定执行成功结果。
+ """
+ return "admin-ok"
+
+
+def _build_json_request(body: dict[str, object]) -> Request:
+ """
+ 构造携带 JSON 请求体的测试 HTTP 请求。
+ """
+ raw = json.dumps(body).encode("utf-8")
+
+ async def _receive() -> dict[str, object]:
+ return {"type": "http.request", "body": raw, "more_body": False}
+
+ return Request(
+ {
+ "type": "http",
+ "method": "POST",
+ "path": "/api/v1/message/web",
+ "headers": [(b"content-type", b"application/json")],
+ "scheme": "http",
+ "server": ("testserver", 80),
+ "client": ("testclient", 123),
+ },
+ receive=_receive,
+ )
+
+
+def test_web_permission_rules_enforce_categories_and_features() -> None:
+ """
+ 网页用户权限规则应严格区分分类、功能开关与超级管理员专属能力。
+ """
+ assert has_web_permission(False, {"admin": True}, "manage") is False
+ assert has_web_permission(True, {}, "manage", "manage.site") is True
+
+ # 仅开通发现但关闭推荐子功能
+ discovery_only = {"discovery": True, "features": {"discovery.recommend": False}}
+ assert authorize_web_operation(False, discovery_only, "music.explore")[0] is True
+ assert authorize_web_operation(False, discovery_only, "recommendation.list")[0] is False
+ assert authorize_web_operation(False, discovery_only, "search.torrents")[0] is False
+ assert authorize_web_operation(False, discovery_only, "config.system.get")[0] is False
+
+ # 订阅功能级细粒度控制
+ tv_only_sub = {"subscribe": True, "features": {"subscribe.movie": False, "subscribe.tv": True}}
+ assert authorize_web_operation(False, tv_only_sub, "subscription.add", media_type="电视剧")[0] is True
+ assert authorize_web_operation(False, tv_only_sub, "subscription.add", media_type="电影")[0] is False
+
+ # 受托管理权限按子功能开放,同时禁止超级管理员专属操作
+ site_manager = {
+ "manage": True,
+ "features": {"manage.site": True, "manage.filemanager": False},
+ }
+ assert authorize_web_operation(False, site_manager, "site.update")[0] is True
+ assert authorize_web_operation(False, site_manager, "storage.mkdir")[0] is False
+ assert authorize_web_operation(False, site_manager, "plugin.install")[0] is False
+ assert authorize_web_operation(False, site_manager, "config.system.update")[0] is False
+ assert authorize_web_operation(False, site_manager, "site.reset")[0] is False
+
+ # 零权限用户仍可读取基础用户/公开配置,但不能访问发现或业务操作
+ assert authorize_web_operation(False, {}, "config.user.get")[0] is True
+ assert authorize_web_operation(False, {}, "media.search")[0] is False
+
+ summary = describe_web_permissions(False, site_manager)
+ assert "普通网页登录用户" in summary
+ assert "文件管理" in summary
+ assert describe_web_permissions(True, site_manager) == ""
+
+
+def test_web_agent_api_never_borrows_superuser_for_public_operations() -> None:
+ """
+ 直接网页会话调用公共资料操作时不得借用超级管理员身份,且按用户实时权限校验。
+ """
+ zero_perm_user = SimpleNamespace(
+ id=9,
+ name="alice",
+ is_active=True,
+ is_superuser=False,
+ permissions={"discovery": False, "search": False, "subscribe": False, "manage": False},
+ )
+ users = SimpleNamespace(async_get_by_id=AsyncMock(return_value=zero_perm_user))
+ gateway = MoviePilotApiTool(session_id="web-agent:9:s1", user_id="9", data=SimpleNamespace(users=users))
+ gateway.set_message_attr(channel=NotificationChannel.WebAgent.value, source="web-agent", username="alice")
+
+ with patch("app.application.security.auth.build_superuser_token_payload") as borrow_admin:
+ raw = asyncio.run(gateway.run("recommendation.list", query={"source": "tmdb_movies"}))
+ payload = json.loads(raw)
+ assert payload["success"] is False
+ assert payload["error"] == "permission_denied"
+ borrow_admin.assert_not_called()
+
+ # 具备 manage.site 的受托管理用户可执行站点更新,无需 superuser
+ site_manager = SimpleNamespace(
+ id=10,
+ name="bob",
+ is_active=True,
+ is_superuser=False,
+ permissions={"manage": True, "features": {"manage.site": True}},
+ )
+ users_mgr = SimpleNamespace(async_get_by_id=AsyncMock(return_value=site_manager))
+ mgr_gateway = MoviePilotApiTool(session_id="web-agent:10:s1", user_id="10", data=SimpleNamespace(users=users_mgr))
+ mgr_gateway.set_message_attr(channel=NotificationChannel.WebAgent.value, source="web-agent", username="bob")
+
+ with patch("app.agent.tools.impl.api.MoviePilotApiExecutor.execute", new=AsyncMock(return_value='{"success":true}')) as execute_mock:
+ allowed_raw = asyncio.run(mgr_gateway.run("site.test", path_params={"site_id": 1}))
+ assert json.loads(allowed_raw)["success"] is True
+ execute_mock.assert_awaited_once()
+
+ denied_raw = asyncio.run(mgr_gateway.run("config.system.get", query={"setting_key": "LLM_API_KEY"}))
+ denied_payload = json.loads(denied_raw)
+ assert denied_payload["success"] is False
+ assert denied_payload["error"] == "permission_denied"
+
+
+def test_web_agent_hides_admin_and_plugin_tools_jobs_and_host_paths() -> None:
+ """
+ 普通网页用户会话不应向模型暴露管理员工具、插件工具、Jobs 中间件或宿主机路径信息。
+ """
+ normal_user = SimpleNamespace(
+ id=12,
+ name="viewer",
+ is_active=True,
+ is_superuser=False,
+ permissions={"discovery": True, "search": False, "subscribe": False, "manage": False},
+ )
+ agent = _get_web_agent_type()(
+ session_id="web-agent:12:chat",
+ user_id="12",
+ channel=NotificationChannel.WebAgent.value,
+ source="web-agent",
+ username="viewer",
+ )
+ normal_tool = _DummyTool(session_id="web-agent:12:chat", user_id="12")
+ admin_tool = _DummyAdminTool(session_id="web-agent:12:chat", user_id="12")
+ plugin_tool = _DummyTool(session_id="web-agent:12:chat", user_id="12", name="plugin_helper")
+ object.__setattr__(plugin_tool, "_agent_tool_source", "plugin:DemoPlugin")
+
+ captured: dict[str, object] = {}
+
+ def _capture_create_agent(**kwargs: object) -> object:
+ captured.update(kwargs)
+ return object()
+
+ fake_llm = SimpleNamespace(
+ _llm_type="fake",
+ model="fake",
+ profile={"max_input_tokens": 64000},
+ )
+ fake_llm.with_retry = lambda: fake_llm
+
+ with (
+ patch("app.agent.web.get_configured_user_id_lookup", return_value=lambda _uid: normal_user),
+ patch.object(agent, "_initialize_tools", return_value=[normal_tool, admin_tool, plugin_tool]),
+ patch.object(agent, "_initialize_subagent_tools", return_value=[normal_tool, admin_tool, plugin_tool]),
+ patch.object(agent, "_initialize_mcp_tools", new=AsyncMock(return_value=[])),
+ patch.object(agent, "_initialize_subagent_mcp_tools", new=AsyncMock(return_value=[])),
+ patch.object(agent, "_initialize_llm", new=AsyncMock(return_value=fake_llm)),
+ patch.object(orchestrator_module, "create_subagent_middlewares", return_value=([], [])),
+ patch.object(orchestrator_module, "create_agent", side_effect=_capture_create_agent),
+ patch.object(orchestrator_module.settings, "LLM_MAX_TOOLS", 0),
+ ):
+ tool_ctx = asyncio.run(agent._build_tool_context(False))
+ agent._refresh_tool_context(tool_ctx)
+ assert tool_ctx["is_admin"] is False
+ assert tool_ctx["web_user_active"] is True
+ assert tool_ctx["web_user_permissions"]["discovery"] is True
+
+ sig_before = asyncio.run(agent._agent_bundle_signature(streaming=False))
+ asyncio.run(agent._create_agent(streaming=False))
+
+ # 权限修改后缓存签名必须变化,触发重建
+ normal_user.permissions["search"] = True
+ updated_ctx = asyncio.run(agent._build_tool_context(False))
+ agent._refresh_tool_context(updated_ctx)
+ sig_after = asyncio.run(agent._agent_bundle_signature(streaming=False))
+ assert sig_after != sig_before
+
+ exposed_names = [getattr(tool, "name", "") for tool in captured["tools"]] # type: ignore[index]
+ assert "dummy_tool" in exposed_names
+ assert "dummy_admin_tool" not in exposed_names
+ assert "plugin_helper" not in exposed_names
+ assert not any(isinstance(mw, JobsMiddleware) for mw in captured["middleware"]) # type: ignore[index]
+
+ system_prompt = str(captured["system_prompt"])
+ assert "" in system_prompt
+ assert "普通网页登录用户" in system_prompt
+ assert "关键运行路径" not in system_prompt
+ assert "已安装的常用系统命令" not in system_prompt
+
+
+def test_non_admin_prompt_omits_host_details_and_subagent_principal_stays_user() -> None:
+ """
+ 非管理员提示词不得暴露宿主机路径,非管理员子代理不得自动提升为 SYSTEM_INTERNAL。
+ """
+ prompt_mgr = PromptManager()
+ non_admin_prompt = prompt_mgr.get_agent_prompt(
+ channel=NotificationChannel.WebAgent.value,
+ is_admin=False,
+ user_permissions_prompt="- 当前会话身份:普通网页登录用户",
+ )
+ assert "关键运行路径" not in non_admin_prompt
+ assert "" in non_admin_prompt
+
+ context = ToolPolicyContext(
+ session_id="web-agent:12:chat",
+ user_id="12",
+ origin=ToolOrigin.AGENT_INTERACTIVE,
+ principal_type=PrincipalType.HUMAN,
+ auth_source=AuthSource.WEB_SESSION,
+ agent_context={"is_admin": False, "web_user_active": True},
+ channel=NotificationChannel.WebAgent.value,
+ source="web-agent",
+ )
+ subagent_context = context.for_subagent()
+ assert subagent_context.principal.role is PrincipalRole.USER
+
+
+def test_policy_middleware_blocks_plugin_and_inactive_web_user() -> None:
+ """
+ 策略中间件必须拦截普通网页用户调用插件工具,并拦截已停用网页用户的全部工具调用。
+ """
+ plugin_tool = _DummyTool(session_id="web-agent:12:chat", user_id="12", name="plugin_action")
+ object.__setattr__(plugin_tool, "_agent_tool_source", "plugin:SecretPlugin")
+ handler = AsyncMock(return_value="should-not-run")
+
+ context = ToolPolicyContext(
+ session_id="web-agent:12:chat",
+ user_id="12",
+ origin=ToolOrigin.AGENT_INTERACTIVE,
+ principal_type=PrincipalType.HUMAN,
+ auth_source=AuthSource.WEB_SESSION,
+ agent_context={"is_admin": False, "web_user_active": True},
+ channel=NotificationChannel.WebAgent.value,
+ source="web-agent",
+ )
+ middleware = AgentPolicyMiddleware(context=context)
+ allowed, result = asyncio.run(
+ middleware.execute_tool_call(tool=plugin_tool, arguments={}, handler=handler, invocation_id="p1")
+ )
+ assert allowed is False
+ assert "插件工具仅允许系统管理员" in str(result.content)
+ handler.assert_not_awaited()
+
+ # 停用用户连普通工具也被拦截
+ inactive_context = ToolPolicyContext(
+ session_id="web-agent:12:chat",
+ user_id="12",
+ origin=ToolOrigin.AGENT_INTERACTIVE,
+ principal_type=PrincipalType.HUMAN,
+ auth_source=AuthSource.WEB_SESSION,
+ agent_context={"is_admin": False, "web_user_active": False},
+ channel=NotificationChannel.WebAgent.value,
+ source="web-agent",
+ )
+ normal_tool = _DummyTool(session_id="web-agent:12:chat", user_id="12")
+ allowed2, result2 = asyncio.run(
+ AgentPolicyMiddleware(context=inactive_context).execute_tool_call(
+ tool=normal_tool, arguments={}, handler=handler, invocation_id="p2"
+ )
+ )
+ assert allowed2 is False
+ assert "已停用" in str(result2.content)
+ handler.assert_not_awaited()
+
+
+def test_non_admin_file_access_blocks_jobs_and_allows_own_uploads(tmp_path, monkeypatch) -> None:
+ """
+ 普通用户禁止读写 Agent 后台 jobs 目录,但允许只读访问自己会话上传的临时附件。
+ """
+ config_path = tmp_path / "config"
+ temp_path = tmp_path / "temp"
+ monkeypatch.setattr(
+ "app.agent.tools.base.get_runtime_setting",
+ lambda name: config_path if name == "CONFIG_PATH" else (temp_path if name == "TEMP_PATH" else None),
+ )
+
+ jobs_file = config_path / "agent" / "jobs" / "daily" / "JOB.md"
+ jobs_file.parent.mkdir(parents=True)
+ jobs_file.write_text("admin job", encoding="utf-8")
+
+ own_upload = temp_path / "agent_uploads" / "web-agent_12_chat" / "note.txt"
+ own_upload.parent.mkdir(parents=True)
+ own_upload.write_text("用户上传内容", encoding="utf-8")
+
+ other_upload = temp_path / "agent_uploads" / "web-agent_99_other" / "secret.txt"
+ other_upload.parent.mkdir(parents=True)
+ other_upload.write_text("他人上传内容", encoding="utf-8")
+
+ reader = ReadFileTool(session_id="web-agent:12:chat", user_id="12")
+ reader.set_agent_context({"is_admin": False})
+ writer = WriteFileTool(session_id="web-agent:12:chat", user_id="12")
+ writer.set_agent_context({"is_admin": False})
+
+ assert "后台任务配置仅允许系统管理员" in asyncio.run(reader.run(str(jobs_file)))
+ assert "后台任务配置仅允许系统管理员" in asyncio.run(writer.run(str(jobs_file), "hijack", overwrite=True))
+ assert "用户上传内容" in asyncio.run(reader.run(str(own_upload)))
+ assert "只能写入" in asyncio.run(writer.run(str(own_upload), "mutate", overwrite=True))
+ assert "只能读取" in asyncio.run(reader.run(str(other_upload)))
+
+
+def test_download_and_download_history_isolate_regular_web_users(monkeypatch) -> None:
+ """
+ 普通搜索/订阅网页用户只能查看自己的下载任务和下载历史,管理用户和管理员可查看全局。
+ """
+ alice = SimpleNamespace(
+ id=5,
+ name="alice",
+ is_active=True,
+ is_superuser=False,
+ permissions={"search": True, "manage": False},
+ )
+ no_perm = SimpleNamespace(
+ id=6,
+ name="guest",
+ is_active=True,
+ is_superuser=False,
+ permissions={"discovery": True, "search": False, "subscribe": False, "manage": False},
+ )
+ manager = SimpleNamespace(
+ id=7,
+ name="ops",
+ is_active=True,
+ is_superuser=False,
+ permissions={"manage": True, "features": {"manage.downloading": True}},
+ )
+
+ assert get_current_download_viewer(alice) is alice
+ assert get_current_download_viewer(manager) is manager
+ with pytest.raises(HTTPException) as exc_info:
+ get_current_download_viewer(no_perm)
+ assert exc_info.value.status_code == 403
+
+ fake_tasks = [
+ SimpleNamespace(username="alice", title="A"),
+ SimpleNamespace(username="bob", title="B"),
+ ]
+ monkeypatch.setattr(download_endpoint, "DownloadChain", lambda: SimpleNamespace(downloading=lambda _name: fake_tasks))
+ assert [t.title for t in download_endpoint.current(_=alice)] == ["A"]
+ assert [t.title for t in download_endpoint.current(_=manager)] == ["A", "B"]
+
+ # 下载历史接口同样按用户隔离
+ query = SimpleNamespace(
+ list_download=AsyncMock(return_value=["alice-record"]),
+ count_download=AsyncMock(return_value=1),
+ )
+ monkeypatch.setattr("app.application.security.user.get_configured_user_id_lookup", lambda: lambda uid: alice if uid == 5 else manager)
+
+ alice_token = TokenPayload(sub=5, username="alice", super_user=False)
+ resp = Response()
+ records = asyncio.run(history_endpoint.download_history(page=1, count=10, query=query, _=alice_token, response=resp))
+ assert records == ["alice-record"]
+ query.list_download.assert_awaited_once_with(page=1, count=10, username="alice")
+ query.count_download.assert_awaited_once_with(username="alice")
+
+ query.list_download.reset_mock()
+ query.count_download.reset_mock()
+ manager_token = TokenPayload(sub=7, username="ops", super_user=False)
+ asyncio.run(history_endpoint.download_history(page=1, count=10, query=query, _=manager_token, response=Response()))
+ query.list_download.assert_awaited_once_with(page=1, count=10, username=None)
+
+
+def test_web_message_endpoint_binds_user_id_and_blocks_non_admin_commands(monkeypatch) -> None:
+ """
+ POST /message/web 允许普通激活用户发送消息并传递真实 user_id,同时拦截非管理员传统斜杠命令。
+ """
+ recorded_calls: list[dict[str, object]] = []
+ fake_chain = SimpleNamespace(handle_message=lambda **kwargs: recorded_calls.append(kwargs))
+ monkeypatch.setattr(message_endpoint, "MessageChain", lambda: fake_chain)
+
+ regular_user = SimpleNamespace(id=15, name="alice", is_superuser=False, is_active=True)
+ result = asyncio.run(
+ message_endpoint.web_message(
+ request=_build_json_request({"text": "帮我找电影"}),
+ current_user=regular_user,
+ )
+ )
+ assert result.success is True
+ assert recorded_calls == [
+ {
+ "channel": NotificationChannel.Web,
+ "source": "alice",
+ "userid": "15",
+ "username": "alice",
+ "text": "帮我找电影",
+ "images": None,
+ "is_channel_admin": False,
+ }
+ ]
+
+ # 普通用户在 Web 渠道发送传统斜杠命令时应被拦截
+ chain = MessageChain()
+ posted: list[object] = []
+ send_event = MagicMock()
+ monkeypatch.setattr(chain, "post_message", lambda message: posted.append(message))
+ monkeypatch.setattr(chain, "eventmanager", SimpleNamespace(send_event=send_event))
+ monkeypatch.setattr(chain, "_plugin_input_interaction_handler", lambda: SimpleNamespace(handle_text=lambda **_kw: False))
+
+ chain._handle_message_core(
+ channel=NotificationChannel.Web,
+ source="alice",
+ userid="15",
+ username="alice",
+ text="/restart",
+ is_channel_admin=False,
+ )
+ send_event.assert_not_called()
+ assert posted and "只有管理员才有权限执行此命令" in str(getattr(posted[0], "title", ""))