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(common): 修复 YAML 解析入口的 CodeCheck 告警

wangjiudongd4d9e41043a6
diff --git a/jiuwenswarm/common/utils.py b/jiuwenswarm/common/utils.py
index a117ae3b3d..0f24a05db2 100644
--- a/jiuwenswarm/common/utils.py
+++ b/jiuwenswarm/common/utils.py
@@ -433,12 +433,19 @@ def fill_template_defaults(
def load_yaml_dict(path: Path) -> dict[str, Any]:
"""安全读取 YAML 字典;缺失或非映射返回空字典,解析错误仍抛出。"""
- # C 实现减少解析开销;未安装 LibYAML 的环境仍使用原有安全解析器。
- loader = getattr(yaml, "CSafeLoader", yaml.SafeLoader)
+ # 直接使用安全 C 解析器,避免通用反序列化入口;无 C 扩展时回退安全接口。
+ loader_class = getattr(yaml, "CSafeLoader", None)
if not path.exists():
return {}
with open(path, "r", encoding="utf-8") as f:
- data = yaml.load(f, Loader=loader)
+ if loader_class is None:
+ data = yaml.safe_load(f)
+ else:
+ loader = loader_class(f)
+ try:
+ data = loader.get_single_data()
+ finally:
+ loader.dispose()
return data if isinstance(data, dict) else {}
diff --git a/tests/unit_tests/common/test_utils_yaml_loader.py b/tests/unit_tests/common/test_utils_yaml_loader.py
index b799133e13..5968b479fd 100644
--- a/tests/unit_tests/common/test_utils_yaml_loader.py
+++ b/tests/unit_tests/common/test_utils_yaml_loader.py
@@ -14,21 +14,23 @@ def test_each_of_four_loads_uses_c_safe_loader_without_caching(tmp_path, monkeyp
template.write_text("nested:\n value: 1\n", encoding="utf-8")
user.write_text("message: 中文\n", encoding="utf-8")
calls = []
- original = yaml.load
- def counted_load(stream, Loader):
- calls.append((stream.name, Loader))
- return original(stream, Loader=Loader)
+ class CountedCSafeLoader(yaml.CSafeLoader):
+ def __init__(self, stream):
+ calls.append(stream.name)
+ super().__init__(stream)
- monkeypatch.setattr(yaml, "load", counted_load)
+ def forbidden_load(*args, **kwargs):
+ pytest.fail("C 解析路径不应调用被 CodeCheck 禁止的通用反序列化入口")
+
+ monkeypatch.setattr(yaml, "CSafeLoader", CountedCSafeLoader)
+ monkeypatch.setattr(yaml, "load", forbidden_load)
first = utils.load_yaml_dict(template)
first["nested"]["value"] = 99
assert utils.load_yaml_dict(template) == {"nested": {"value": 1}}
assert utils.load_yaml_dict(template) == {"nested": {"value": 1}}
assert utils.load_yaml_dict(user) == {"message": "中文"}
- assert calls == [
- (str(path), yaml.CSafeLoader) for path in (template, template, template, user)
- ]
+ assert calls == [str(path) for path in (template, template, template, user)]
def test_safe_loader_fallback_when_c_extension_is_unavailable(tmp_path, monkeypatch):
@@ -36,15 +38,36 @@ def test_safe_loader_fallback_when_c_extension_is_unavailable(tmp_path, monkeypa
config = tmp_path / "fallback.yaml"
config.write_text("message: 中文\nflag: true\n", encoding="utf-8")
calls = []
- original = yaml.load
+ original = yaml.safe_load
- def counted_load(stream, Loader):
- calls.append(Loader)
- return original(stream, Loader=Loader)
+ def counted_load(stream):
+ calls.append(stream.name)
+ return original(stream)
- monkeypatch.setattr(yaml, "load", counted_load)
+ monkeypatch.setattr(yaml, "safe_load", counted_load)
assert utils.load_yaml_dict(config) == {"message": "中文", "flag": True}
- assert calls == [yaml.SafeLoader]
+ assert calls == [str(config)]
+
+
[email protected](not hasattr(yaml, "CSafeLoader"), reason="当前 PyYAML 未提供 C 扩展")
[email protected]("text", ["value: 1\n", "value: [unterminated\n", "value: !!python/object/apply:builtins.str [123]\n"])
+def test_c_loader_is_disposed_on_success_and_parse_errors(tmp_path, monkeypatch, text):
+ config = tmp_path / "dispose.yaml"
+ config.write_text(text, encoding="utf-8")
+ disposed = []
+
+ class TrackedCSafeLoader(yaml.CSafeLoader):
+ def dispose(self):
+ disposed.append(self)
+ super().dispose()
+
+ monkeypatch.setattr(yaml, "CSafeLoader", TrackedCSafeLoader)
+ if text == "value: 1\n":
+ assert utils.load_yaml_dict(config) == {"value": 1}
+ else:
+ with pytest.raises(yaml.YAMLError):
+ utils.load_yaml_dict(config)
+ assert len(disposed) == 1
def _typed(value):
@@ -79,7 +102,10 @@ def test_values_and_types_match_safe_load(tmp_path, text):
"value: !!python/object/apply:builtins.str [123]\n",
"first: 1\n---\nsecond: 2\n",
])
-def test_invalid_documents_and_python_object_tags_remain_rejected(tmp_path, text):
[email protected]("without_c_extension", [False, True])
+def test_invalid_documents_and_python_object_tags_remain_rejected(tmp_path, monkeypatch, text, without_c_extension):
+ if without_c_extension:
+ monkeypatch.delattr(yaml, "CSafeLoader", raising=False)
config = tmp_path / "invalid.yaml"
config.write_text(text, encoding="utf-8")
with pytest.raises(yaml.YAMLError) as caught: