test_read_file_tool.py
11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
"""read_file tool unit tests — sandbox security, path normalization, truncation."""
import pytest
import tempfile
import shutil
from pathlib import Path
from unittest.mock import MagicMock, AsyncMock
from app.service.active_session_service import ActiveSessionService
from app.service.agent_hub import AgentHub
from agentscope.message._message_block import TextBlock
# ── Fixture: 创建使用临时目录的 AgentHub ─────────────────────────
@pytest.fixture
def sandbox_root(tmp_path):
"""Create a temporary project root with test files."""
# Create app/ subdirectory so AgentHub path resolution works
app_dir = tmp_path / "app"
app_dir.mkdir()
# Create test files
(tmp_path / "config.json").write_text('{"key": "value"}', encoding="utf-8")
(tmp_path / "skills").mkdir()
(tmp_path / "skills" / "SKILL.md").write_text("# My Skill", encoding="utf-8")
# Create a large file (>10000 chars)
(tmp_path / "large.txt").write_text("A" * 15000, encoding="utf-8")
# Create a nested file
(tmp_path / "a" / "b").mkdir(parents=True)
(tmp_path / "a" / "b" / "deep.txt").write_text("deep content", encoding="utf-8")
return tmp_path
@pytest.fixture
def hub_with_sandbox(sandbox_root):
"""Create an AgentHub whose read_file tool is sandboxed to tmp_path."""
from app.config.settings import AgentConfig
test_agents = {
"test_steward": AgentConfig(
name="测试管家", code="1",
prompt="测试prompt", is_steward=True,
),
}
mock_loader = MagicMock()
mock_model_config = MagicMock()
mock_model_config.model_name = "test-model"
mock_model_config.api_key = "test-key"
mock_model_config.api_base = "http://test"
mock_loader.load_models.return_value = {"main": mock_model_config}
mock_loader.load_skills_from_toolkit.return_value = {}
session_service = ActiveSessionService()
im_service = MagicMock()
im_service.send_message = AsyncMock(return_value={"code": 200})
hub = AgentHub(
config_loader=mock_loader,
session_service=session_service,
im_service=im_service,
preloaded_agents=test_agents,
)
# Override the read_file tool with one rooted at sandbox_root
from agentscope.tool import Toolkit
read_file_func = _make_read_file_with_root(sandbox_root)
hub.toolkit.register_tool_function(
read_file_func,
func_name="read_file",
group_name="basic",
namesake_strategy="override",
)
for agent_tk in hub.agent_toolkits.values():
agent_tk.register_tool_function(
read_file_func,
func_name="read_file",
group_name="basic",
namesake_strategy="override",
)
return hub
def _make_read_file_with_root(root_dir: Path):
"""Create a read_file closure with a custom root directory."""
root_dir = root_dir.resolve()
async def read_file(file_path: str):
from agentscope.tool._response import ToolResponse
try:
normalized = file_path.replace("\\", "/")
if normalized.startswith("./"):
normalized = normalized[2:]
full_path = (root_dir / normalized).resolve()
if not str(full_path).startswith(str(root_dir)):
return ToolResponse(
content=[TextBlock(type="text", text="❌ Access denied: path escapes project root")]
)
if not full_path.exists():
return ToolResponse(
content=[TextBlock(type="text", text=f"❌ File not found: {file_path}")]
)
if not full_path.is_file():
return ToolResponse(
content=[TextBlock(type="text", text=f"❌ Not a file: {file_path}")]
)
content = full_path.read_text(encoding="utf-8")
if len(content) > 10000:
content = content[:10000] + "\n...[truncated]"
return ToolResponse(content=[TextBlock(type="text", text=content)])
except Exception as e:
return ToolResponse(
content=[TextBlock(type="text", text=f"❌ Error reading file: {str(e)}")]
)
return read_file
# ── Helper: 提取 ToolResponse 文本 ──
def _extract_text(resp):
"""Extract text from ToolResponse (content blocks may be dicts or TextBlock)."""
block = resp.content[0]
if isinstance(block, dict):
return block["text"]
return block.text
# ═══════════════════════════════════════════════════════════════════
# read_file 工具测试
# ═══════════════════════════════════════════════════════════════════
class TestReadFileTool:
async def _call_tool(self, toolkit, file_path: str):
"""Helper: call read_file via toolkit and return collected responses."""
gen = await toolkit.call_tool_function(
{"name": "read_file", "input": {"file_path": file_path}}
)
results = []
async for resp in gen:
results.append(resp)
return results
@pytest.mark.asyncio
async def test_read_existing_file(self, hub_with_sandbox):
"""成功读取项目根目录下的文件"""
results = await self._call_tool(hub_with_sandbox.toolkit, "config.json")
text = _extract_text(results[-1])
assert '"key": "value"' in text
@pytest.mark.asyncio
async def test_read_nested_file(self, hub_with_sandbox):
"""读取嵌套目录中的文件"""
results = await self._call_tool(hub_with_sandbox.toolkit, "a/b/deep.txt")
text = _extract_text(results[-1])
assert text == "deep content"
@pytest.mark.asyncio
async def test_read_skill_md(self, hub_with_sandbox):
"""读取 SKILL.md 文件"""
results = await self._call_tool(hub_with_sandbox.toolkit, "skills/SKILL.md")
text = _extract_text(results[-1])
assert "# My Skill" in text
@pytest.mark.asyncio
async def test_file_not_found(self, hub_with_sandbox):
"""文件不存在 → 返回错误信息"""
results = await self._call_tool(hub_with_sandbox.toolkit, "nonexistent.txt")
text = _extract_text(results[-1])
assert "❌" in text
assert "not found" in text.lower() or "Not found" in text
@pytest.mark.asyncio
async def test_not_a_file_directory(self, hub_with_sandbox):
"""路径是目录而非文件 → 返回错误"""
results = await self._call_tool(hub_with_sandbox.toolkit, "skills")
text = _extract_text(results[-1])
assert "❌" in text
assert "Not a file" in text or "not a file" in text.lower()
@pytest.mark.asyncio
async def test_path_traversal_blocked(self, hub_with_sandbox):
"""路径穿越攻击 ../../etc/passwd → 沙箱拒绝"""
results = await self._call_tool(hub_with_sandbox.toolkit, "../../etc/passwd")
text = _extract_text(results[-1])
assert "Access denied" in text or "escapes" in text.lower()
@pytest.mark.asyncio
async def test_path_traversal_with_dot_prefix(self, hub_with_sandbox):
"""./../../etc/passwd → 沙箱拒绝"""
results = await self._call_tool(hub_with_sandbox.toolkit, "./../../etc/passwd")
text = _extract_text(results[-1])
assert "Access denied" in text or "escapes" in text.lower()
@pytest.mark.asyncio
async def test_large_file_truncated(self, hub_with_sandbox):
"""超过 10000 字符的文件被截断"""
results = await self._call_tool(hub_with_sandbox.toolkit, "large.txt")
text = _extract_text(results[-1])
assert "[truncated]" in text
assert len(text) < 15000
@pytest.mark.asyncio
async def test_path_with_leading_dot_slash(self, hub_with_sandbox):
"""./config.json 路径前缀被正确规范化"""
results = await self._call_tool(hub_with_sandbox.toolkit, "./config.json")
text = _extract_text(results[-1])
assert '"key": "value"' in text
@pytest.mark.asyncio
async def test_path_with_backslash(self, hub_with_sandbox):
"""Windows 风格路径 a\\b\\deep.txt 被规范化"""
results = await self._call_tool(hub_with_sandbox.toolkit, "a\\b\\deep.txt")
text = _extract_text(results[-1])
assert text == "deep content"
@pytest.mark.asyncio
async def test_absolute_path_outside_sandbox_blocked(self, hub_with_sandbox):
"""绝对路径指向沙箱外 → 拒绝"""
results = await self._call_tool(hub_with_sandbox.toolkit, "/etc/hostname")
text = _extract_text(results[-1])
assert "Access denied" in text or "not found" in text.lower() or "Error" in text
class TestReadFileToolRegistration:
"""Verify read_file is properly registered in the toolkit."""
def test_read_file_in_toolkit_schemas(self):
"""read_file 出现在 toolkit JSON schema 中"""
from app.config.settings import AgentConfig
test_agents = {
"test_steward": AgentConfig(
name="测试管家", code="1",
prompt="测试prompt", is_steward=True,
),
}
mock_loader = MagicMock()
mock_model_config = MagicMock()
mock_model_config.model_name = "test-model"
mock_model_config.api_key = "test-key"
mock_model_config.api_base = "http://test"
mock_loader.load_models.return_value = {"main": mock_model_config}
mock_loader.load_skills_from_toolkit.return_value = {}
im_service = MagicMock()
im_service.send_message = AsyncMock(return_value={"code": 200})
hub = AgentHub(
config_loader=mock_loader,
session_service=ActiveSessionService(),
im_service=im_service,
preloaded_agents=test_agents,
)
schemas = hub.toolkit.get_json_schemas()
names = [s["function"]["name"] for s in schemas]
assert "read_file" in names
# Verify schema has file_path parameter
read_file_schema = next(s for s in schemas if s["function"]["name"] == "read_file")
assert "file_path" in read_file_schema["function"]["parameters"]["properties"]
def test_read_file_in_all_agent_toolkits(self):
"""read_file 注册到所有 agent 的专属 toolkit"""
from app.config.settings import AgentConfig
test_agents = {
"test_steward": AgentConfig(
name="测试管家", code="1",
prompt="测试prompt", is_steward=True,
),
}
mock_loader = MagicMock()
mock_model_config = MagicMock()
mock_model_config.model_name = "test-model"
mock_model_config.api_key = "test-key"
mock_model_config.api_base = "http://test"
mock_loader.load_models.return_value = {"main": mock_model_config}
mock_loader.load_skills_from_toolkit.return_value = {}
im_service = MagicMock()
im_service.send_message = AsyncMock(return_value={"code": 200})
hub = AgentHub(
config_loader=mock_loader,
session_service=ActiveSessionService(),
im_service=im_service,
preloaded_agents=test_agents,
)
for agent_code, agent_tk in hub.agent_toolkits.items():
names = [s["function"]["name"] for s in agent_tk.get_json_schemas()]
assert "read_file" in names, f"read_file missing from {agent_code} toolkit"