Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
[security] fix(bot): prevent image tool from reading host files outside sandbox (#1702)
Hinotobi7b9d43fdb63e
diff --git a/bot/tests/test_image_tool_sandbox.py b/bot/tests/test_image_tool_sandbox.pynew file mode 100644index 000000000..e1656d98b--- /dev/null+++ b/bot/tests/test_image_tool_sandbox.py@@ -0,0 +1,195 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Regression tests for image tool sandbox file handling."""++import base64+import importlib.util+import sys+import types+from pathlib import Path+from types import SimpleNamespace++import pytest+++class _FakeSandbox:+ def __init__(self, files=None, error=None):+ self.files = files or {}+ self.error = error+ self.read_paths = []++ async def read_file_bytes(self, path: str) -> bytes:+ self.read_paths.append(path)+ if self.error:+ raise self.error+ return self.files[path]+++class _SandboxManager:+ def __init__(self, sandbox):+ self._sandbox = sandbox++ async def get_sandbox(self, session_key):+ return self._sandbox+++def _load_image_module(monkeypatch):+ """Load the image tool module directly so this regression stays isolated."""+ repo_root = Path(__file__).resolve().parents[2]+ image_path = repo_root / "bot" / "vikingbot" / "agent" / "tools" / "image.py"++ base_mod = types.ModuleType("vikingbot.agent.tools.base")++ class Tool:+ pass++ class ToolContext:+ pass++ base_mod.Tool = Tool+ base_mod.ToolContext = ToolContext++ events_mod = types.ModuleType("vikingbot.bus.events")++ class OutboundMessage:+ def __init__(self, **kwargs):+ self.__dict__.update(kwargs)++ events_mod.OutboundMessage = OutboundMessage++ utils_mod = types.ModuleType("vikingbot.utils")+ utils_mod.get_data_path = lambda: repo_root++ monkeypatch.setitem(sys.modules, "vikingbot", types.ModuleType("vikingbot"))+ monkeypatch.setitem(sys.modules, "vikingbot.agent", types.ModuleType("vikingbot.agent"))+ monkeypatch.setitem(+ sys.modules, "vikingbot.agent.tools", types.ModuleType("vikingbot.agent.tools")+ )+ monkeypatch.setitem(sys.modules, "vikingbot.agent.tools.base", base_mod)+ monkeypatch.setitem(sys.modules, "vikingbot.bus", types.ModuleType("vikingbot.bus"))+ monkeypatch.setitem(sys.modules, "vikingbot.bus.events", events_mod)+ monkeypatch.setitem(sys.modules, "vikingbot.utils", utils_mod)++ spec = importlib.util.spec_from_file_location("image_tool_under_test", image_path)+ module = importlib.util.module_from_spec(spec)+ assert spec.loader is not None+ spec.loader.exec_module(module)+ return module+++def _load_image_tool(monkeypatch):+ return _load_image_module(monkeypatch).ImageGenerationTool+++async def test_image_tool_uses_sandbox_for_local_paths(monkeypatch, tmp_path):+ secret = tmp_path / "host-secret.png"+ secret.write_bytes(b"OPENVIKING_HOST_SECRET_MARKER")+ sandbox = _FakeSandbox(error=PermissionError("outside sandbox"))+ context = SimpleNamespace(session_key="session", sandbox_manager=_SandboxManager(sandbox))++ ImageGenerationTool = _load_image_tool(monkeypatch)+ tool = ImageGenerationTool()++ with pytest.raises(PermissionError):+ await tool._parse_image_data(str(secret), context)++ assert sandbox.read_paths == [str(secret)]+++async def test_image_tool_reads_sandbox_local_file_paths(monkeypatch):+ sandbox = _FakeSandbox(files={"image.png": b"SANDBOX_IMAGE_BYTES"})+ context = SimpleNamespace(session_key="session", sandbox_manager=_SandboxManager(sandbox))++ ImageGenerationTool = _load_image_tool(monkeypatch)+ tool = ImageGenerationTool()+ data_uri, format_type = await tool._parse_image_data("image.png", context)++ assert sandbox.read_paths == ["image.png"]+ assert format_type == "data"+ assert data_uri.startswith("data:image/png;base64,")+ assert base64.b64decode(data_uri.split(",", 1)[1]) == b"SANDBOX_IMAGE_BYTES"+++async def test_image_tool_keeps_data_uri_support_without_sandbox_context(monkeypatch):+ ImageGenerationTool = _load_image_tool(monkeypatch)+ tool = ImageGenerationTool()+ data_uri = "data:image/png;base64,UE5H"++ parsed, format_type = await tool._parse_image_data(data_uri)++ assert parsed == data_uri+ assert format_type == "data"+++def test_image_tool_documents_mask_sandbox_local_paths(monkeypatch):+ ImageGenerationTool = _load_image_tool(monkeypatch)+ tool = ImageGenerationTool()++ mask_description = tool.parameters["properties"]["mask"]["description"]++ assert "sandbox-local" in mask_description+++async def test_image_tool_keeps_url_support_without_sandbox_context(monkeypatch):+ ImageGenerationTool = _load_image_tool(monkeypatch)+ tool = ImageGenerationTool()+ image_url = "https://example.com/image.png"++ parsed, format_type = await tool._parse_image_data(image_url)++ assert parsed == image_url+ assert format_type == "url"+++async def test_image_tool_rejects_local_paths_without_sandbox_context(monkeypatch):+ ImageGenerationTool = _load_image_tool(monkeypatch)+ tool = ImageGenerationTool()++ with pytest.raises(ValueError, match="sandbox context"):+ await tool._parse_image_data("image.png")+++async def test_edit_mode_reads_base_image_and_mask_from_sandbox(monkeypatch, tmp_path):+ sandbox = _FakeSandbox(+ files={+ "base.png": b"SANDBOX_BASE_IMAGE_BYTES",+ "mask.png": b"SANDBOX_MASK_IMAGE_BYTES",+ }+ )+ context = SimpleNamespace(session_key="session", sandbox_manager=_SandboxManager(sandbox))+ module = _load_image_module(monkeypatch)+ monkeypatch.setattr(module, "get_data_path", lambda: tmp_path)+ captured_kwargs = {}++ async def fake_image_edit(**kwargs):+ captured_kwargs.update(kwargs)+ return SimpleNamespace(+ data=[SimpleNamespace(b64_json=base64.b64encode(b"OUTPUT").decode())]+ )++ monkeypatch.setattr(module.litellm, "aimage_edit", fake_image_edit)+ tool = module.ImageGenerationTool(gen_image_model="openai/dall-e-2")++ result = await tool.execute(+ context,+ mode="edit",+ prompt="edit safely",+ base_image="base.png",+ mask="mask.png",+ send_to_user=False,+ )++ assert sandbox.read_paths == ["base.png", "mask.png"]+ assert captured_kwargs["image"].startswith("data:image/png;base64,")+ assert captured_kwargs["mask"].startswith("data:image/png;base64,")+ assert (+ base64.b64decode(captured_kwargs["image"].split(",", 1)[1]) == b"SANDBOX_BASE_IMAGE_BYTES"+ )+ assert base64.b64decode(captured_kwargs["mask"].split(",", 1)[1]) == b"SANDBOX_MASK_IMAGE_BYTES"+ assert result.startswith("生成图片:")diff --git a/bot/vikingbot/agent/tools/image.py b/bot/vikingbot/agent/tools/image.pyindex fab682e45..c3d35b208 100644--- a/bot/vikingbot/agent/tools/image.py+++ b/bot/vikingbot/agent/tools/image.py@@ -5,7 +5,6 @@ import loggingimport mimetypesimport uuidfrom io import BytesIO-from pathlib import Pathfrom typing import Any, Awaitable, Callableimport httpx@@ -44,11 +43,11 @@ class ImageGenerationTool(Tool):},"base_image": {"type": "string",- "description": "Base image for edit/variation mode: base64 data URI or image file path (required for edit and variation modes)",+ "description": "Base image for edit/variation mode: base64 data URI, image URL, or sandbox-local image file path (required for edit and variation modes)",},"mask": {"type": "string",- "description": "Mask image for edit mode: base64 data URI or image URL (optional, transparent areas indicate where to edit)",+ "description": "Mask image for edit mode: base64 data URI, image URL, or sandbox-local image file path (optional, transparent areas indicate where to edit)",},"size": {"type": "string",@@ -105,9 +104,11 @@ class ImageGenerationTool(Tool):"""Check if the current model is a Seedream model."""return "seedream" in self.gen_image_model.lower()- async def _parse_image_data(self, image_str: str) -> tuple[str, str]:+ async def _parse_image_data(+ self, image_str: str, tool_context: "ToolContext | None" = None+ ) -> tuple[str, str]:"""- Parse image from base64 data URI, URL, or file path.+ Parse image from base64 data URI, URL, or sandbox-local file path.Returns: (image_data, format_type) where format_type is "data" or "url""""if image_str.startswith("data:"):@@ -115,10 +116,14 @@ class ImageGenerationTool(Tool):elif image_str.startswith("http://") or image_str.startswith("https://"):return image_str, "url"else:+ if tool_context is None:+ raise ValueError("Local image paths require a sandbox context")mime_type, _ = mimetypes.guess_type(image_str)if not mime_type:mime_type = "application/octet-stream"- base64_str = base64.b64encode(Path(image_str).read_bytes()).decode("utf-8")+ sandbox = await tool_context.sandbox_manager.get_sandbox(tool_context.session_key)+ image_bytes = await sandbox.read_file_bytes(image_str)+ base64_str = base64.b64encode(image_bytes).decode("utf-8")data_uri = f"data:{mime_type};base64,{base64_str}"return data_uri, "data"@@ -157,6 +162,7 @@ class ImageGenerationTool(Tool):async def _seedream_image_to_image(self,+ tool_context: "ToolContext",base_image: str,prompt: str,strength: float,@@ -164,7 +170,7 @@ class ImageGenerationTool(Tool):n: int,) -> Any:"""Shared method for Seedream image-to-image generation (used by edit and variation modes)."""- base_image_data, base_format = await self._parse_image_data(base_image)+ base_image_data, base_format = await self._parse_image_data(base_image, tool_context)kwargs = self._build_common_kwargs(size=size,n=n,@@ -217,6 +223,7 @@ class ImageGenerationTool(Tool):elif mode == "edit":if self._is_seedream_model:response = await self._seedream_image_to_image(+ tool_context=tool_context,base_image=base_image, # type: ignore[arg-type]prompt=prompt, # type: ignore[arg-type]strength=0.7,@@ -224,12 +231,14 @@ class ImageGenerationTool(Tool):n=n,)else:- base_image_data, base_format = await self._parse_image_data(base_image) # type: ignore[arg-type]+ base_image_data, base_format = await self._parse_image_data(+ base_image, tool_context+ ) # type: ignore[arg-type]edit_kwargs = self._build_common_kwargs(size=size, n=n, include_style=False)edit_kwargs["prompt"] = promptedit_kwargs["image"] = base_image_dataif mask:- mask_data, mask_format = await self._parse_image_data(mask)+ mask_data, mask_format = await self._parse_image_data(mask, tool_context)if mask_format == "bytes":edit_kwargs["mask"] = BytesIO(mask_data) # type: ignoreelse:@@ -239,6 +248,7 @@ class ImageGenerationTool(Tool):elif mode == "variation":if self._is_seedream_model:response = await self._seedream_image_to_image(+ tool_context=tool_context,base_image=base_image, # type: ignore[arg-type]prompt="Create a variation of this image",strength=0.3,@@ -246,7 +256,9 @@ class ImageGenerationTool(Tool):n=n,)else:- base_image_data, base_format = await self._parse_image_data(base_image) # type: ignore[arg-type]+ base_image_data, base_format = await self._parse_image_data(+ base_image, tool_context+ ) # type: ignore[arg-type]var_kwargs = self._build_common_kwargs(size=size, n=n, include_style=False)var_kwargs["image"] = base_image_dataresponse = await litellm.aimage_variation(**var_kwargs)diff --git a/bot/vikingbot/sandbox/backends/direct.py b/bot/vikingbot/sandbox/backends/direct.pyindex c7ea299b1..3d16a8379 100644--- a/bot/vikingbot/sandbox/backends/direct.py+++ b/bot/vikingbot/sandbox/backends/direct.py@@ -1,17 +1,14 @@"""Direct backend implementation - executes commands directly on host without sandboxing."""import asyncio-import osfrom pathlib import Path-from typing import TYPE_CHECKING, Any+from typing import Anyfrom loguru import logger-from vikingbot.sandbox.base import SandboxBackend-from vikingbot.sandbox.backends import register_backend--from vikingbot.config.schema import SandboxConfig, SessionKey+from vikingbot.sandbox.backends import register_backend+from vikingbot.sandbox.base import SandboxBackend@register_backend("direct")@@ -105,7 +102,7 @@ class DirectBackend(SandboxBackend):"""Get the current working directory (uses actual host cwd)."""return str(self._workspace)- async def read_file(self, path: str) -> str:+ async def read_file_bytes(self, path: str) -> bytes:sandbox_path = Path(path)if not sandbox_path.is_absolute():sandbox_path = self._workspace / path@@ -115,7 +112,10 @@ class DirectBackend(SandboxBackend):raise FileNotFoundError(f"File not found: {path}")if not sandbox_path.is_file():raise IOError(f"Not a file: {path}")- return sandbox_path.read_text(encoding="utf-8")+ return await asyncio.to_thread(sandbox_path.read_bytes)++ async def read_file(self, path: str) -> str:+ return (await self.read_file_bytes(path)).decode("utf-8")async def write_file(self, path: str, content: str) -> None:sandbox_path = Path(path)@@ -162,4 +162,4 @@ class DirectBackend(SandboxBackend):returnif resolved != workspace and workspace not in resolved.parents:- raise PermissionError(f"Path outside workspace: {path}")\ No newline at end of file+ raise PermissionError(f"Path outside workspace: {path}")diff --git a/bot/vikingbot/sandbox/base.py b/bot/vikingbot/sandbox/base.pyindex 2e794691a..b5e8696a5 100644--- a/bot/vikingbot/sandbox/base.py+++ b/bot/vikingbot/sandbox/base.py@@ -1,5 +1,6 @@"""Abstract interface for sandbox backends."""+import asynciofrom abc import ABC, abstractmethodfrom pathlib import Pathfrom typing import Any@@ -73,14 +74,14 @@ class SandboxBackend(ABC):return self.workspace / path.lstrip("/")return self.workspace / path- async def read_file(self, path: str) -> str:- """Read file from sandbox (default implementation: host filesystem).+ async def read_file_bytes(self, path: str) -> bytes:+ """Read file bytes from sandbox (default implementation: host filesystem).Args:path: Path to file (absolute or relative to sandbox_cwd)Returns:- File content as string+ File content as bytesRaises:FileNotFoundError: If file doesn't exist@@ -93,7 +94,23 @@ class SandboxBackend(ABC):raise FileNotFoundError(f"File not found: {path}")if not sandbox_path.is_file():raise IOError(f"Not a file: {path}")- return sandbox_path.read_text(encoding="utf-8")+ return await asyncio.to_thread(sandbox_path.read_bytes)++ async def read_file(self, path: str) -> str:+ """Read file from sandbox (default implementation: host filesystem).++ Args:+ path: Path to file (absolute or relative to sandbox_cwd)++ Returns:+ File content as string++ Raises:+ FileNotFoundError: If file doesn't exist+ IOError: If read fails+ PermissionError: If path outside workspace and restriction is enabled+ """+ return (await self.read_file_bytes(path)).decode("utf-8")async def write_file(self, path: str, content: str) -> None:"""Write file to sandbox (default implementation: host filesystem).