DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Restrict code execution scope and enforce default imports
RinZ2730326bce3bd7
diff --git a/src/agents/research/research_pipeline.py b/src/agents/research/research_pipeline.pyindex c842d910b..4e1af5dff 100644--- a/src/agents/research/research_pipeline.py+++ b/src/agents/research/research_pipeline.py@@ -56,7 +56,7 @@ from src.agents.research.agents import (from src.agents.research.data_structures import DynamicTopicQueuefrom src.agents.research.utils.citation_manager import CitationManagerfrom src.logging import get_logger-from src.tools.code_executor import run_code+from src.tools.code_executor import run_code, DEFAULT_SAFE_IMPORTSfrom src.tools.paper_search_tool import PaperSearchToolfrom src.tools.query_item_tool import query_numbered_itemfrom 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 timeouttool_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:diff --git a/src/agents/solve/main_solver.py b/src/agents/solve/main_solver.pyindex 4031c2338..57ba528dd 100644--- a/src/agents/solve/main_solver.py+++ b/src/agents/solve/main_solver.py@@ -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_IMPORTSresult = await run_code(language="python",code=code,timeout=30,assets_dir=artifacts_dir,+ allowed_imports=DEFAULT_SAFE_IMPORTS,)parts: list[str] = []diff --git a/src/tools/code_executor.py b/src/tools/code_executor.pyindex 1b1b306dd..8c56c2d59 100644--- a/src/tools/code_executor.py+++ b/src/tools/code_executor.py@@ -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_loggerfrom 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)