Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix:优化安全护栏config生成项

Zql99f7c453ef360e
diff --git a/docs/zh/permissions_config_architecture.md b/docs/zh/permissions_config_architecture.md
index f886a6f661..10a3fcd918 100644
--- a/docs/zh/permissions_config_architecture.md
+++ b/docs/zh/permissions_config_architecture.md
@@ -17,7 +17,7 @@
flowchart TB
subgraph sources [配置来源]
YAML["config.yaml::permissions 全局段<br/>标准版未命中 agents[id]"]
- AGENTS["config.yaml::permissions.agents[id]<br/>标准版精确命中整段替换"]
+ AGENTS["config.yaml::permissions.agents[id]<br/>稀疏覆盖∪包内模板"]
TPL[("permissions_template.body<br/>企业 Agent 级基线")]
OVL["session overlay<br/>企业会话内存叠加"]
end
@@ -76,14 +76,16 @@ flowchart TB
| 函数 | 职责 |
| --- | --- |
| `setup_permissions_agent_base()` | 绑定当前 Task 的 Agent 级 body(企业模板或标准版 yaml `agents[id]`) |
-| `resolve_yaml_agent_permissions_body()` | 标准版精确匹配 `permissions.agents[agent_id]`;企业版恒为未命中 |
+| `resolve_yaml_agent_permissions_body()` | 命中覆盖或种子 id:返回「包内模板 ∪ 稀疏覆盖」;其它未命中 / 企业版为 `None` |
+| `get_shipped_template_permissions_config()` | 包内 `resources/config.yaml` 的 permissions 全局段(剥掉 `agents`),作 agent 缺省底 |
+| `get_yaml_agent_permissions_overlay()` | 标准版返回 yaml 稀疏覆盖段(供落盘);未命中 / 企业版为 `None` |
| `resolve_permissions_body_from_enterprise()` | 从企业配置 `permissions` 槽位取首个启用模板 body |
| `get_global_permissions_config()` | 标准版全局策略段(yaml 去掉 `agents`),不读 Agent base |
| `get_base_permissions_config()` | Agent base 优先,否则全局 yaml(**不再读实例级 permissions_config 表**) |
| `get_effective_permissions_config()` | 企业版:base + 会话 overlay;其他:yaml/base |
| `apply_permissions_config_payload()` | 刷新进程缓存(显式 body 或 yaml fallback) |
| `reload_permissions_from_gateway_db()` | 冷启动:仅刷新为 yaml fallback(模板 / `agents[id]` 在请求路径注入) |
-| `persist_permissions_mutate()` | 标准版:`persist_target_agent_id` 命中则写 `agents[id]`,否则写全局并保留 `agents`;企业 session 写 overlay;企业 base 仅内存 |
+| `persist_permissions_mutate()` | 标准版:`persist_target_agent_id` 命中则写稀疏 `agents[id]`(种子首次建空覆盖,只落 mutate 字段);否则写全局并保留已有 `agents`(不自动 seed);企业 session 写 overlay;企业 base 仅内存 |
| `clear_permissions_config_cache()` | 清进程缓存 |
@@ -138,16 +140,16 @@ permissions:
tool_bindings: {}
external_directory: {...} # 旧键,加载时自动迁移到 file_guard.global
agents: # 标准版保留键,不是工具名;Gateway GET 会剥离
- office-excel: # 精确匹配 runtime agent_id;整段替换,不与全局合并
- enabled: true
+ office-excel: # 精确匹配 runtime agent_id;稀疏覆盖叠到包内模板
+ enabled: true # 按需写入;未写的字段回落包内模板(非用户全局)
tools: {...}
```
`permissions.agents` 只在标准版生效:
-- **精确命中** `agents[agent_id]` 且 value 为 dict:该 Agent 使用该完整 body(内层再嵌套 `agents` 忽略)。
-- **未命中**:使用全局段。种子 id(`office-excel`)在护栏全局 persist 或专属落盘时从当前全局模板 copy-on-write 建桶;已有桶不覆盖。其它 id 仍不自动建桶。
-- **Web RPC** 带 `request.agent_id` 且命中时读写 `agents[id]`;无 `agent_id` 保持全局(不要把 `extract_ids` 的默认 `"default"` 当成命中)。
+- **精确命中** `agents[agent_id]` 或 **种子 id**(如 `office-excel`,可尚未建桶):生效策略 = **包内模板** ∪ 稀疏覆盖(`tools` / `file_guard` 深合并,其余键覆盖;内层再嵌套 `agents` 忽略)。缺省不受用户全局 permissions 改动影响。
+- **其它 id 未命中**:使用用户全局段。专属落盘时种子 id 可按需建空覆盖桶,**只写入本次 mutate 字段**;**全局 persist 不自动 seed**。
+- **Web RPC** 带 `request.agent_id` 且命中(或种子可建桶)时读写 `agents[id]`;无 `agent_id` 保持全局(不要把 `extract_ids` 的默认 `"default"` 当成命中)。
- **HITL 落盘** 在 `build_permission_rail` 时钉住 `persist_target_agent_id`(supervisor Task 不继承 ContextVar)。
- **snapshot**:专属 body / 企业模板 rail 必须返回 `None`,使用构建时的 `_static_config`。
- **企业版**:不解析 yaml `agents`,只用 `template_ref.permissions`。
@@ -558,4 +560,4 @@ Manager REST ──HTTP──► Gateway Receiver ──► gateway.db
## 十一、一句话总结
-**企业版**:策略存在 `permissions_template`,经 Agent `template_ref.permissions` 绑定到具体 Agent,请求路径注入 `PERMISSIONS_AGENT_BASE`(可叠加会话 overlay)。**标准版 / 单机**:`config.yaml::permissions` 全局段 + 可选 `permissions.agents[agent_id]` 精确整段替换(如 Excel `office-excel`);未命中共享全局。**执行层**仅在 AgentServer 由 PermissionRail / 引擎做 allow/ask/deny。实例级 `permissions_config` 表与对应 REST/WS 推送已废弃并移除。
\ No newline at end of file
+**企业版**:策略存在 `permissions_template`,经 Agent `template_ref.permissions` 绑定到具体 Agent,请求路径注入 `PERMISSIONS_AGENT_BASE`(可叠加会话 overlay)。**标准版 / 单机**:用户全局 `permissions` + 可选 `permissions.agents[agent_id]` 稀疏覆盖(如 Excel `office-excel`);种子 / 命中桶的缺省底为**包内模板**,不受用户全局改动影响。**执行层**仅在 AgentServer 由 PermissionRail / 引擎做 allow/ask/deny。实例级 `permissions_config` 表与对应 REST/WS 推送已废弃并移除。
\ No newline at end of file
diff --git "a/docs/zh/\345\267\245\345\205\267\346\235\203\351\231\220\344\270\216\345\256\211\345\205\250\351\230\262\346\212\244.md" "b/docs/zh/\345\267\245\345\205\267\346\235\203\351\231\220\344\270\216\345\256\211\345\205\250\351\230\262\346\212\244.md"
index 416c3c2206..ff295d04a6 100644
--- "a/docs/zh/\345\267\245\345\205\267\346\235\203\351\231\220\344\270\216\345\256\211\345\205\250\351\230\262\346\212\244.md"
+++ "b/docs/zh/\345\267\245\345\205\267\346\235\203\351\231\220\344\270\216\345\256\211\345\205\250\351\230\262\346\212\244.md"
@@ -14,7 +14,7 @@
| **三级动作** | `allow` 直接执行;`ask` 需用户确认(Web/CLI 等);`deny` 拒绝。 |
| **主开关** | `permissions.enabled`;关闭后引擎对工具调用返回 `allow`(仍建议生产环境保持开启)。 |
| **策略模式** | `permissions.schema: tiered_policy`(及兼容别名)时启用**分层策略**;否则走旧版工具级匹配。 |
-| **标准版按 Agent 隔离** | yaml 保留键 `permissions.agents[agent_id]`:精确命中则该 Agent 整段替换使用专属 body(不与全局合并);未命中用全局。企业版忽略此键,只用 `template_ref.permissions`。 |
+| **标准版按 Agent 隔离** | yaml 保留键 `permissions.agents[agent_id]`:命中(或种子如 `office-excel`)时生效 = **包内模板** ∪ 稀疏覆盖(按需写入;缺省不受用户全局改动影响);其它未命中用用户全局。企业版忽略此键,只用 `template_ref.permissions`。 |
| **参与校验的通道** | 仅当 `channel_id` 属于 `web` / `acp` / `cli` 等引擎约定集合时才做工具权限检查;其它通道可跳过。 |
diff --git a/jiuwenswarm/agents/harness/common/rails/permissions/__init__.py b/jiuwenswarm/agents/harness/common/rails/permissions/__init__.py
index 4227d7a45b..5fb241521f 100644
--- a/jiuwenswarm/agents/harness/common/rails/permissions/__init__.py
+++ b/jiuwenswarm/agents/harness/common/rails/permissions/__init__.py
@@ -18,7 +18,10 @@ from jiuwenswarm.agents.harness.common.rails.permissions.config_loader import (
get_global_permissions_config,
get_permissions_agent_base,
get_permissions_session_id,
+ get_shipped_template_permissions_config,
+ get_yaml_agent_permissions_overlay,
lookup_standard_permissions_agent_id,
+ merge_agent_permissions_overlay,
merge_session_permissions_overlay,
normalize_permissions_agent_id,
persist_permissions_mutate,
@@ -45,8 +48,11 @@ __all__ = [
"get_global_permissions_config",
"get_permissions_agent_base",
"get_permissions_session_id",
+ "get_shipped_template_permissions_config",
+ "get_yaml_agent_permissions_overlay",
"is_enterprise",
"lookup_standard_permissions_agent_id",
+ "merge_agent_permissions_overlay",
"merge_session_permissions_overlay",
"normalize_permissions_agent_id",
"persist_permissions_mutate",
diff --git a/jiuwenswarm/agents/harness/common/rails/permissions/config_loader.py b/jiuwenswarm/agents/harness/common/rails/permissions/config_loader.py
index c1364ffbaf..c90816a79f 100644
--- a/jiuwenswarm/agents/harness/common/rails/permissions/config_loader.py
+++ b/jiuwenswarm/agents/harness/common/rails/permissions/config_loader.py
@@ -16,13 +16,14 @@ logger = logging.getLogger(__name__)
PersistScope = Literal["session", "base"]
-# 标准版 yaml 保留键:按 agent_id 分桶的完整 permissions body,不是工具名。
+# 标准版 yaml 保留键:按 agent_id 分桶的 permissions 覆盖段(稀疏),不是工具名。
PERMISSIONS_AGENTS_KEY = "agents"
-# 护栏全局 persist / 专属落盘未命中时,从当前全局模板克隆这些桶(已有则不覆盖)。
+# 种子 id:未建桶时专属落盘仍可写入 agents[id](按需稀疏,非整段克隆全局)。
SEED_PERMISSIONS_AGENT_IDS: tuple[str, ...] = ("office-excel",)
_cached_global: dict[str, Any] | None = None
_cached_agents: dict[str, dict[str, Any]] = {}
+_cached_template_permissions: dict[str, Any] | None = None
_cache_source: str | None = None
_session_overlays: dict[str, dict[str, Any]] = {}
@@ -71,9 +72,10 @@ def get_permissions_agent_base() -> dict[str, Any] | None:
def clear_permissions_config_cache() -> None:
- global _cached_global, _cached_agents, _cache_source
+ global _cached_global, _cached_agents, _cached_template_permissions, _cache_source
_cached_global = None
_cached_agents = {}
+ _cached_template_permissions = None
_cache_source = None
@@ -139,31 +141,6 @@ def _is_seed_permissions_agent_id(agent_id: str | None) -> bool:
return bool(normalized) and normalized in SEED_PERMISSIONS_AGENT_IDS
-def _clone_permissions_template_body(source: dict[str, Any] | None) -> dict[str, Any]:
- """从全局/模板 permissions 段克隆一份可作 ``agents[id]`` 的 body。"""
- return sanitize_agent_permissions_body(strip_permissions_agents(source))
-
-
-def _seed_missing_agent_buckets(
- agents_table: dict[str, Any],
- template_body: dict[str, Any],
-) -> bool:
- """按种子 id 补桶;已有 dict 不覆盖。返回是否新建过桶。"""
- cloned = _clone_permissions_template_body(template_body)
- created = False
- for agent_id in SEED_PERMISSIONS_AGENT_IDS:
- existing = agents_table.get(agent_id)
- if isinstance(existing, dict):
- continue
- agents_table[agent_id] = copy.deepcopy(cloned)
- created = True
- logger.info(
- "[permissions_config] seeded yaml agents[%s] from global template",
- agent_id,
- )
- return created
-
-
def _parse_agents_table(raw: dict[str, Any] | None) -> dict[str, dict[str, Any]]:
if not isinstance(raw, dict):
return {}
@@ -192,6 +169,12 @@ def _ingest_permissions_raw(raw: dict[str, Any], source: str) -> dict[str, Any]:
def _load_yaml_cache(*, force_reload: bool = False) -> dict[str, Any]:
+ """加载 yaml 缓存,返回剥掉 ``agents`` 后的全局段。
+
+ 副作用:标准版同步填充 ``_cached_agents``。调用方若需要 ``agents[id]``
+ 覆盖表,必须读 ``_cached_agents``,**禁止**对返回值做 ``.get("agents")``
+ (返回值永远不含该键)。
+ """
global _cached_global
if not force_reload and _cached_global is not None:
return copy.deepcopy(_cached_global)
@@ -199,40 +182,147 @@ def _load_yaml_cache(*, force_reload: bool = False) -> dict[str, Any]:
return _ingest_permissions_raw(raw, "yaml")
+def _ensure_yaml_permissions_cache(*, force_reload: bool = False) -> None:
+ """确保 ``_cached_global`` / ``_cached_agents`` 已从 yaml 加载。"""
+ _load_yaml_cache(force_reload=force_reload)
+
+
def get_global_permissions_config(*, force_reload: bool = False) -> dict[str, Any]:
- """标准版全局策略段(yaml 去掉 ``agents``)。不读 ``PERMISSIONS_AGENT_BASE``。"""
+ """标准版全局策略段(yaml 去掉 ``agents``)。不读 ``PERMISSIONS_AGENT_BASE``。
+
+ 该段为「包内模板 ∪ 用户 override」的生效全局,可被 UI 改写。
+ Agent 稀疏覆盖的缺省底请用 ``get_shipped_template_permissions_config``。
+ """
return _load_yaml_cache(force_reload=force_reload)
-def resolve_yaml_agent_permissions_body(agent_id: str | None) -> dict[str, Any] | None:
- """标准版精确匹配 ``permissions.agents[agent_id]``;企业版不解析 yaml ``agents``。
+def get_shipped_template_permissions_config(*, force_reload: bool = False) -> dict[str, Any]:
+ """包内 ``resources/config.yaml`` 的 permissions 全局段(剥掉 ``agents``)。
+
+ 不受用户全局 permissions 改动影响;供 ``agents[id]`` 稀疏覆盖的缺省底。
+ """
+ global _cached_template_permissions
+ if not force_reload and _cached_template_permissions is not None:
+ return copy.deepcopy(_cached_template_permissions)
+ from jiuwenswarm.common.utils import load_yaml_dict, resolve_shipped_template_config_path
+
+ raw = load_yaml_dict(resolve_shipped_template_config_path()).get("permissions")
+ _cached_template_permissions = strip_permissions_agents(
+ raw if isinstance(raw, dict) else {}
+ )
+ return copy.deepcopy(_cached_template_permissions)
+
+
+def merge_agent_permissions_overlay(
+ base: dict[str, Any] | None,
+ overlay: dict[str, Any] | None,
+) -> dict[str, Any]:
+ """以 base(通常为包内模板)为底,agent 稀疏覆盖叠加上去。
- value 非 dict 视为未命中。命中后返回已剥掉内层 ``agents`` 的完整 body。
+ ``tools`` / ``file_guard`` 深合并,其余键覆盖。
+ """
+ merged = strip_permissions_agents(base if isinstance(base, dict) else {})
+ if not isinstance(overlay, dict) or not overlay:
+ return merged
+
+ overlay_clean = sanitize_agent_permissions_body(overlay)
+
+ overlay_tools = overlay_clean.get("tools")
+ if isinstance(overlay_tools, dict):
+ tools = merged.get("tools")
+ if not isinstance(tools, dict):
+ tools = {}
+ merged["tools"] = tools
+ tools.update(copy.deepcopy(overlay_tools))
+
+ overlay_overrides = overlay_clean.get("approval_overrides")
+ if isinstance(overlay_overrides, list):
+ base_list = list(merged.get("approval_overrides") or [])
+ existing = {
+ _approval_override_fingerprint(item)
+ for item in base_list
+ if isinstance(item, dict)
+ }
+ for item in overlay_overrides:
+ if not isinstance(item, dict):
+ continue
+ fingerprint = _approval_override_fingerprint(item)
+ if fingerprint in existing:
+ continue
+ base_list.append(copy.deepcopy(item))
+ existing.add(fingerprint)
+ merged["approval_overrides"] = base_list
+
+ overlay_fg = overlay_clean.get("file_guard")
+ if isinstance(overlay_fg, dict):
+ fg = merged.get("file_guard")
+ if not isinstance(fg, dict):
+ fg = {}
+ merged["file_guard"] = fg
+ _deep_merge_file_guard(fg, overlay_fg)
+
+ for key, value in overlay_clean.items():
+ if key in ("tools", "approval_overrides", "file_guard"):
+ continue
+ merged[key] = copy.deepcopy(value)
+
+ return merged
+
+
+def get_yaml_agent_permissions_overlay(agent_id: str | None) -> dict[str, Any] | None:
+ """标准版返回 yaml ``permissions.agents[id]`` 稀疏覆盖段;企业版 / 未命中为 ``None``。
+
+ 不与模板/全局合并;供落盘 mutate。内层再嵌套 ``agents`` 已剥离。
+
+ 实现注意:全局缓存 API(``_load_yaml_cache`` / ``get_global_permissions_config``)
+ 返回值已剥掉 ``agents``,不能对返回 dict 做 ``.get("agents")``。覆盖表只存在于
+ ``_cached_agents``(由 ``_ingest_permissions_raw`` 在加载时填充)。
"""
if is_enterprise():
return None
normalized = normalize_permissions_agent_id(agent_id)
if not normalized:
return None
- _load_yaml_cache()
+ _ensure_yaml_permissions_cache()
body = _cached_agents.get(normalized)
if not isinstance(body, dict):
return None
return copy.deepcopy(body)
+def resolve_yaml_agent_permissions_body(agent_id: str | None) -> dict[str, Any] | None:
+ """标准版解析 ``permissions.agents[agent_id]``;企业版不解析 yaml ``agents``。
+
+ - 命中稀疏覆盖,或种子 id(如 ``office-excel``)尚未建桶:返回
+ 「包内模板 ∪ 覆盖」生效 body(缺省不受用户全局改动影响)。
+ - 其它 id 未命中:``None``(调用方回落用户全局)。
+ """
+ if is_enterprise():
+ return None
+ normalized = normalize_permissions_agent_id(agent_id)
+ if not normalized:
+ return None
+ overlay = get_yaml_agent_permissions_overlay(normalized)
+ if overlay is None and not _is_seed_permissions_agent_id(normalized):
+ return None
+ return merge_agent_permissions_overlay(
+ get_shipped_template_permissions_config(),
+ overlay or {},
+ )
+
+
def resolve_permissions_persist_target(agent_id: str | None) -> str | None:
- """命中 yaml ``agents[id]`` 时返回该 id(写专属 body);否则 ``None``(写全局)。
+ """命中 yaml ``agents[id]`` 时返回该 id(写专属覆盖);否则 ``None``(写全局)。
企业版恒为 ``None``。种子 id(如 ``office-excel``)未命中仍返回该 id,persist 时
- 从全局模板 copy-on-write 建桶。其它 id 未命中不新建。
+ 按需建空覆盖桶并只写入本次 mutate 字段。其它 id 未命中不新建。
"""
if is_enterprise():
return None
normalized = normalize_permissions_agent_id(agent_id)
if not normalized:
return None
- if resolve_yaml_agent_permissions_body(normalized) is not None:
+ if get_yaml_agent_permissions_overlay(normalized) is not None:
return normalized
if _is_seed_permissions_agent_id(normalized):
return normalized
@@ -523,9 +613,9 @@ def persist_permissions_mutate(
"""变更 permissions 并持久化。
- 标准版:写 ``config.yaml``。``persist_target_agent_id`` 命中 yaml
- ``agents[id]`` 时只更新该 body;种子 id 未命中则从全局模板 copy-on-write
- 建桶后写入;其它未命中写全局。全局 persist 会补齐缺失的种子桶(如
- ``office-excel``),已有桶不覆盖。
+ ``agents[id]`` 时只更新该稀疏覆盖段;种子 id 未命中则建空覆盖后只写入
+ 本次 mutate 字段(不整段克隆全局)。其它未命中写全局。全局 persist
+ **不**自动 seed ``agents`` 桶。
- 企业版 + ``persist_scope='session'``:仅更新指定会话的内存 overlay。
- 企业版 + ``persist_scope='base'``:仅更新进程内存缓存(不再写 permissions_config 表;
Agent 级策略请改 permissions_template)。不读写 yaml ``agents``。
@@ -569,10 +659,11 @@ def persist_permissions_mutate(
return permissions
target_id = normalize_permissions_agent_id(persist_target_agent_id)
- agent_body = resolve_yaml_agent_permissions_body(target_id) if target_id else None
- if target_id and agent_body is not None:
- permissions = copy.deepcopy(agent_body)
- old_permissions = copy.deepcopy(permissions)
+ agent_overlay = get_yaml_agent_permissions_overlay(target_id) if target_id else None
+ if target_id and agent_overlay is not None:
+ permissions = copy.deepcopy(agent_overlay)
+ template_base = get_shipped_template_permissions_config()
+ old_effective = merge_agent_permissions_overlay(template_base, permissions)
mutate_fn(permissions)
permissions = sanitize_agent_permissions_body(permissions)
_persist_agent_permissions_to_yaml(target_id, permissions)
@@ -582,24 +673,28 @@ def persist_permissions_mutate(
target_id,
source,
)
- _sync_skill_grants(old_permissions, permissions)
- return permissions
+ new_effective = merge_agent_permissions_overlay(template_base, permissions)
+ _sync_skill_grants(old_effective, new_effective)
+ return new_effective
if target_id and _is_seed_permissions_agent_id(target_id):
- permissions = _clone_permissions_template_body(get_global_permissions_config())
- old_permissions = copy.deepcopy(permissions)
+ permissions: dict[str, Any] = {}
+ template_base = get_shipped_template_permissions_config()
+ old_effective = copy.deepcopy(template_base)
mutate_fn(permissions)
permissions = sanitize_agent_permissions_body(permissions)
_persist_agent_permissions_to_yaml(target_id, permissions)
_cached_agents[target_id] = copy.deepcopy(permissions)
logger.info(
- "[permissions_config] standard agent persist copy-on-write "
- "agent_id=%s source=%s",
+ "[permissions_config] standard agent persist sparse-create "
+ "agent_id=%s source=%s keys=%s",
target_id,
source,
+ sorted(permissions.keys()),
)
- _sync_skill_grants(old_permissions, permissions)
- return permissions
+ new_effective = merge_agent_permissions_overlay(template_base, permissions)
+ _sync_skill_grants(old_effective, new_effective)
+ return new_effective
permissions = get_global_permissions_config()
if not isinstance(permissions, dict):
@@ -655,17 +750,15 @@ def _persist_global_permissions_to_yaml(permissions: dict[str, Any]) -> None:
section = copy.deepcopy(permissions)
section.pop(PERMISSIONS_AGENTS_KEY, None)
- if not is_enterprise():
- if agents_table is None:
- agents_table = {}
- _seed_missing_agent_buckets(agents_table, section)
- section[PERMISSIONS_AGENTS_KEY] = agents_table
- for agent_id, body in agents_table.items():
- normalized = normalize_permissions_agent_id(str(agent_id) if agent_id is not None else None)
- if normalized and isinstance(body, dict):
- _cached_agents[normalized] = sanitize_agent_permissions_body(body)
- elif agents_table is not None:
+ if agents_table is not None:
section[PERMISSIONS_AGENTS_KEY] = agents_table
+ if not is_enterprise():
+ for agent_id, body in agents_table.items():
+ normalized = normalize_permissions_agent_id(
+ str(agent_id) if agent_id is not None else None
+ )
+ if normalized and isinstance(body, dict):
+ _cached_agents[normalized] = sanitize_agent_permissions_body(body)
if not isinstance(data, dict):
data = {}
data["permissions"] = section
diff --git a/tests/unit_tests/agents/harness/test_permissions_agents_isolation.py b/tests/unit_tests/agents/harness/test_permissions_agents_isolation.py
index b2542cc3cd..c4bab44843 100644
--- a/tests/unit_tests/agents/harness/test_permissions_agents_isolation.py
+++ b/tests/unit_tests/agents/harness/test_permissions_agents_isolation.py
@@ -1,7 +1,7 @@
# coding: utf-8
# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""标准版 ``permissions.agents[agent_id]`` 精确整段替换隔离。"""
+"""标准版 ``permissions.agents[agent_id]`` 稀疏覆盖 + 包内模板缺省底。"""
from __future__ import annotations
@@ -37,14 +37,14 @@ def _load_config_loader():
loader = _load_config_loader()
+# 用户全局(可被 UI 改写)
_RAW: dict[str, Any] = {
"enabled": False,
"schema": "tiered_policy",
- "tools": {"bash": "allow"},
+ "tools": {"bash": "allow", "write_file": "deny"},
"agents": {
"office-excel": {
"enabled": True,
- "schema": "tiered_policy",
"tools": {"bash": "deny"},
"agents": {"nested": {"enabled": False}},
},
@@ -52,9 +52,23 @@ _RAW: dict[str, Any] = {
},
}
+# 包内模板缺省底(与用户全局刻意不同,用于证明不跟全局走)
+_TEMPLATE: dict[str, Any] = {
+ "enabled": False,
+ "schema": "tiered_policy",
+ "permission_mode": "normal",
+ "defaults": {"*": "allow"},
+ "tools": {"bash": "allow", "write_file": "allow", "mcp_exec_command": "ask"},
+}
+
@pytest.fixture(autouse=True)
-def _reset_permissions_cache():
+def _reset_permissions_cache(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(
+ loader,
+ "get_shipped_template_permissions_config",
+ lambda *, force_reload=False: copy.deepcopy(_TEMPLATE),
+ )
loader.clear_permissions_config_cache()
yield
loader.clear_permissions_config_cache()
@@ -81,10 +95,20 @@ def test_resolve_yaml_agent_permissions_hit_miss(monkeypatch, standard_edition):
body = loader.resolve_yaml_agent_permissions_body("office-excel")
assert body is not None
+ # 生效 = 包内模板 ∪ 稀疏覆盖;write_file 跟模板 allow,不跟用户全局 deny
assert body["enabled"] is True
+ assert body["schema"] == "tiered_policy"
assert body["tools"]["bash"] == "deny"
+ assert body["tools"]["write_file"] == "allow"
+ assert body["tools"]["mcp_exec_command"] == "ask"
assert "agents" not in body
+ overlay = loader.get_yaml_agent_permissions_overlay("office-excel")
+ assert overlay is not None
+ assert overlay["enabled"] is True
+ assert "schema" not in overlay
+ assert "write_file" not in overlay.get("tools", {})
+
assert loader.resolve_yaml_agent_permissions_body("missing") is None
assert loader.resolve_yaml_agent_permissions_body("bad") is None
assert loader.resolve_yaml_agent_permissions_body(None) is None
@@ -93,7 +117,40 @@ def test_resolve_yaml_agent_permissions_hit_miss(monkeypatch, standard_edition):
global_cfg = loader.get_global_permissions_config()
assert "agents" not in global_cfg
assert global_cfg["enabled"] is False
- assert global_cfg["tools"]["bash"] == "allow"
+ assert global_cfg["tools"]["write_file"] == "deny"
+
+ # 回归:全局段剥掉 agents 后,覆盖表仍须从 _cached_agents 可读(不得 .get("agents"))
+ overlay_after_global = loader.get_yaml_agent_permissions_overlay("office-excel")
+ assert overlay_after_global is not None
+ assert overlay_after_global["tools"]["bash"] == "deny"
+ assert loader.get_yaml_agent_permissions_overlay("missing") is None
+
+
+def test_overlay_not_readable_from_stripped_global_return(monkeypatch, standard_edition):
+ """评审回归:_load_yaml_cache 返回值不含 agents,只能读 _cached_agents。"""
+ monkeypatch.setattr(loader, "_load_permissions_from_yaml", lambda: copy.deepcopy(_RAW))
+ loader.clear_permissions_config_cache()
+
+ stripped = loader._load_yaml_cache()
+ assert "agents" not in stripped
+ assert stripped.get(loader.PERMISSIONS_AGENTS_KEY, {}) == {}
+
+ # 错误写法会恒为空;正确写法读进程侧 _cached_agents
+ assert loader._cached_agents.get("office-excel") is not None
+ assert loader.get_yaml_agent_permissions_overlay("office-excel") is not None
+
+
+def test_seed_without_overlay_uses_template(monkeypatch, standard_edition):
+ monkeypatch.setattr(
+ loader,
+ "_load_permissions_from_yaml",
+ lambda: {"enabled": False, "tools": {"write_file": "deny"}},
+ )
+ body = loader.resolve_yaml_agent_permissions_body("office-excel")
+ assert body is not None
+ assert body["tools"]["write_file"] == "allow"
+ assert body["tools"]["mcp_exec_command"] == "ask"
+ assert loader.get_yaml_agent_permissions_overlay("office-excel") is None
def test_enterprise_ignores_yaml_agents(monkeypatch):
@@ -101,6 +158,7 @@ def test_enterprise_ignores_yaml_agents(monkeypatch):
monkeypatch.setattr(loader, "_load_permissions_from_yaml", lambda: copy.deepcopy(_RAW))
assert loader.resolve_yaml_agent_permissions_body("office-excel") is None
+ assert loader.get_yaml_agent_permissions_overlay("office-excel") is None
global_cfg = loader.get_global_permissions_config()
assert "agents" not in global_cfg
@@ -192,7 +250,7 @@ def test_persist_miss_does_not_create_agent_bucket(tmp_path, monkeypatch, standa
assert "office-excel" in perms["agents"]
-def test_persist_global_seeds_office_excel_from_template(tmp_path, monkeypatch, standard_edition):
+def test_persist_global_does_not_seed_office_excel(tmp_path, monkeypatch, standard_edition):
payload = {
"enabled": False,
"schema": "tiered_policy",
@@ -209,16 +267,10 @@ def test_persist_global_seeds_office_excel_from_template(tmp_path, monkeypatch,
data = yaml.safe_load(yaml_path.read_text(encoding="utf-8"))
perms = data["permissions"]
assert perms["enabled"] is True
- agent = perms["agents"]["office-excel"]
- assert agent["enabled"] is True
- assert agent["schema"] == "tiered_policy"
- assert agent["tools"]["bash"] == "allow"
- assert agent["tools"]["write_file"] == "ask"
- assert agent["file_guard"]["enabled"] is True
- assert "agents" not in agent
+ assert "agents" not in perms
-def test_persist_global_does_not_overwrite_seeded_office_excel(
+def test_persist_global_does_not_overwrite_existing_office_excel(
tmp_path, monkeypatch, standard_edition
):
yaml_path = _install_yaml(tmp_path, monkeypatch, copy.deepcopy(_RAW))
@@ -234,16 +286,16 @@ def test_persist_global_does_not_overwrite_seeded_office_excel(
assert "write_file" not in agent["tools"]
-def test_persist_office_excel_miss_copy_on_write(tmp_path, monkeypatch, standard_edition):
+def test_persist_office_excel_miss_sparse_create(tmp_path, monkeypatch, standard_edition):
payload = {
"enabled": False,
"schema": "tiered_policy",
- "tools": {"bash": "allow", "write_file": "allow"},
+ "tools": {"bash": "allow", "write_file": "deny"},
}
yaml_path = _install_yaml(tmp_path, monkeypatch, payload)
def mutate(perms: dict[str, Any]) -> None:
- perms.setdefault("tools", {})["write_file"] = "deny"
+ perms.setdefault("tools", {})["write_file"] = "ask"
loader.persist_permissions_mutate(
mutate,
@@ -253,11 +305,49 @@ def test_persist_office_excel_miss_copy_on_write(tmp_path, monkeypatch, standard
)
data = yaml.safe_load(yaml_path.read_text(encoding="utf-8"))
perms = data["permissions"]
- assert perms["tools"]["write_file"] == "allow"
+ assert perms["tools"]["write_file"] == "deny"
agent = perms["agents"]["office-excel"]
- assert agent["tools"]["bash"] == "allow"
- assert agent["tools"]["write_file"] == "deny"
- assert "agents" not in agent
+ assert agent == {"tools": {"write_file": "ask"}}
+
+ effective = loader.resolve_yaml_agent_permissions_body("office-excel")
+ assert effective is not None
+ # bash / mcp 来自模板,不来自用户全局
+ assert effective["tools"]["bash"] == "allow"
+ assert effective["tools"]["write_file"] == "ask"
+ assert effective["tools"]["mcp_exec_command"] == "ask"
+ assert effective["schema"] == "tiered_policy"
+
+
+def test_persist_office_excel_enabled_toggle_sparse(
+ tmp_path, monkeypatch, standard_edition
+):
+ payload = {
+ "enabled": False,
+ "schema": "tiered_policy",
+ "defaults": {"*": "allow"},
+ "tools": {"bash": "deny", "mcp_exec_command": "deny"},
+ }
+ yaml_path = _install_yaml(tmp_path, monkeypatch, payload)
+
+ def mutate(perms: dict[str, Any]) -> None:
+ perms["enabled"] = True
+
+ loader.persist_permissions_mutate(
+ mutate,
+ persist_scope="base",
+ persist_target_agent_id="office-excel",
+ source="permissions_config_rpc",
+ )
+ data = yaml.safe_load(yaml_path.read_text(encoding="utf-8"))
+ agent = data["permissions"]["agents"]["office-excel"]
+ assert agent == {"enabled": True}
+
+ effective = loader.resolve_yaml_agent_permissions_body("office-excel")
+ assert effective is not None
+ assert effective["enabled"] is True
+ # 用户全局改成 deny 也不影响:仍读模板
+ assert effective["tools"]["bash"] == "allow"
+ assert effective["tools"]["mcp_exec_command"] == "ask"
def test_lookup_standard_permissions_agent_id():