test_read_file_tool.py 11.6 KB
"""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"