mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-05 01:10:16 +08:00
Merge pull request #196 from RinZ27/feat/code-executor-hardening
Restrict code execution scope and enforce import whitelist
This commit is contained in:
@@ -56,7 +56,7 @@ from src.agents.research.agents import (
|
||||
from src.agents.research.data_structures import DynamicTopicQueue
|
||||
from src.agents.research.utils.citation_manager import CitationManager
|
||||
from src.logging import get_logger
|
||||
from src.tools.code_executor import run_code
|
||||
from src.tools.code_executor import run_code, DEFAULT_SAFE_IMPORTS
|
||||
from src.tools.paper_search_tool import PaperSearchTool
|
||||
from src.tools.query_item_tool import query_numbered_item
|
||||
from src.tools.rag_tool import rag_search
|
||||
@@ -364,6 +364,7 @@ class ResearchPipeline:
|
||||
run_code,
|
||||
language="python",
|
||||
code=query,
|
||||
allowed_imports=DEFAULT_SAFE_IMPORTS,
|
||||
max_retries=1,
|
||||
timeout=30, # Wrapper timeout
|
||||
tool_name="run_code",
|
||||
@@ -379,7 +380,7 @@ class ResearchPipeline:
|
||||
mode="hybrid",
|
||||
max_retries=max_retries,
|
||||
timeout=default_timeout,
|
||||
tool_name="rag_search(hybrid)",
|
||||
tool_name=f"rag_search(hybrid)",
|
||||
)
|
||||
return json.dumps(res, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
|
||||
@@ -585,13 +585,14 @@ class MainSolver:
|
||||
code = await self._generate_code(intent)
|
||||
|
||||
# Step 2: Execute
|
||||
from src.tools.code_executor import run_code
|
||||
from src.tools.code_executor import run_code, DEFAULT_SAFE_IMPORTS
|
||||
|
||||
result = await run_code(
|
||||
language="python",
|
||||
code=code,
|
||||
timeout=30,
|
||||
assets_dir=artifacts_dir,
|
||||
allowed_imports=DEFAULT_SAFE_IMPORTS,
|
||||
)
|
||||
|
||||
parts: list[str] = []
|
||||
|
||||
@@ -22,6 +22,13 @@ RUN_CODE_ALLOWED_ROOTS_ENV = "RUN_CODE_ALLOWED_ROOTS"
|
||||
DEFAULT_WORKSPACE_NAME = "run_code_workspace"
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
# Standard scientific and utility libraries allowed by default
|
||||
DEFAULT_SAFE_IMPORTS = [
|
||||
"math", "numpy", "pandas", "matplotlib", "plt", "seaborn",
|
||||
"scipy", "statsmodels", "json", "datetime", "re", "collections",
|
||||
"itertools", "functools", "random", "time", "statistics", "sympy"
|
||||
]
|
||||
|
||||
from src.logging import get_logger
|
||||
from src.services.path_service import get_path_service
|
||||
|
||||
@@ -139,10 +146,9 @@ class WorkspaceManager:
|
||||
self.base_dir = path_service.get_run_code_workspace_dir().resolve()
|
||||
|
||||
# Determine allowed root paths list
|
||||
# Default includes project root and user directory
|
||||
# Default includes only the user directory for safety (avoid project root access)
|
||||
path_service = get_path_service()
|
||||
self.allowed_roots: list[Path] = [
|
||||
PROJECT_ROOT.resolve(),
|
||||
path_service.user_data_dir.resolve(),
|
||||
]
|
||||
|
||||
@@ -289,7 +295,14 @@ class CodeExecutionEnvironment:
|
||||
timeout: int,
|
||||
assets_dir: Path | None,
|
||||
) -> tuple[str, str, int, float]:
|
||||
env = os.environ.copy()
|
||||
# Filter environment variables to prevent leaking API keys to the code process
|
||||
env = {}
|
||||
# Only include safe environment variables
|
||||
safe_vars = {"PYTHONIOENCODING", "PATH", "LANG", "LC_ALL"}
|
||||
for k, v in os.environ.items():
|
||||
if k in safe_vars or k.startswith("PYTHON"):
|
||||
env[k] = v
|
||||
|
||||
env["PYTHONIOENCODING"] = "utf-8"
|
||||
|
||||
with self.workspace.create_temp_dir() as temp_dir:
|
||||
@@ -334,6 +347,11 @@ async def run_code(
|
||||
raise ValueError(f"Unsupported language: {language}, currently only Python is supported")
|
||||
|
||||
WORKSPACE_MANAGER.ensure_initialized()
|
||||
|
||||
# Apply default whitelist if none provided
|
||||
if allowed_imports is None:
|
||||
allowed_imports = DEFAULT_SAFE_IMPORTS
|
||||
|
||||
ImportGuard.validate(code, allowed_imports)
|
||||
|
||||
assets_path = WORKSPACE_MANAGER.resolve_assets_dir(assets_dir)
|
||||
|
||||
Reference in New Issue
Block a user