Personal AI, On Personal Devices
Python
feat(security): enforce configured directories across file tool entry points (#1070)
Wagner Gadea Lorenzf802978aebd7
diff --git a/docs/user-guide/system-access.md b/docs/user-guide/system-access.mdindex 83064513..1d1bbd38 100644--- a/docs/user-guide/system-access.md+++ b/docs/user-guide/system-access.md@@ -63,9 +63,23 @@ python -c "from openjarvis.core.config import load_config; print(load_config().t| `code_interpreter` | Python in a subprocess, behind a coarse pattern blocklist. |`file_read` and `file_write` take an `allowed_dirs` argument that limits them to-a set of directories, but no config key populates it. When it's empty every path-is allowed. If you want a filesystem jail today, use the container sandbox-instead of relying on these tools to enforce one.+a set of directories. When the argument is not passed they use+`[security] allowed_dirs` from `config.toml`:++```toml+[security]+allowed_dirs = ["/home/user/workspace"]+```++When the list is empty (the default) every path is allowed. This restricts only+these two tools; `shell_exec`, `apply_patch` and `code_interpreter` are not+affected, so use the container sandbox if you need a real filesystem jail.+Relative file names resolve inside the first allowed directory. Paths using+`..` or symlinks must still resolve within an allowed directory. Use an array+of non-empty directory paths; invalid or unreadable configuration prevents the+file tools from loading instead of removing their restrictions. Explicit+configuration supplied to the CLI, SDK, or system builder uses the same policy,+including managed-agent streaming, scheduled ticks, and ephemeral turns.### Sensitive filenamesdiff --git a/src/openjarvis/agents/executor.py b/src/openjarvis/agents/executor.pyindex 1c324c0d..e04a6b91 100644--- a/src/openjarvis/agents/executor.py+++ b/src/openjarvis/agents/executor.py@@ -180,7 +180,13 @@ class AgentExecutor:if isinstance(registered, BaseTool):instances.append(registered)elif isinstance(registered, type) and issubclass(registered, BaseTool):- instances.append(registered())+ from openjarvis.tools._paths import file_tool_kwargs++ instances.append(+ registered(+ **file_tool_kwargs(name, getattr(self._system, "config", None))+ )+ )execution_cls = (agent_cls@@ -461,6 +467,7 @@ class AgentExecutor:mcp_tools=mcp_tools,mcp_clients=mcp_clients,knowledge_db_path=getattr(self._system, "knowledge_db_path", None),+ app_config=getattr(self._system, "config", None),)self._toolkit_local.current = resolved_toolkittool_instances = resolved_toolkit.instancesdiff --git a/src/openjarvis/agents/tool_resolver.py b/src/openjarvis/agents/tool_resolver.pyindex 404b92b1..4ea6b373 100644--- a/src/openjarvis/agents/tool_resolver.py+++ b/src/openjarvis/agents/tool_resolver.py@@ -235,6 +235,7 @@ def instantiate_registered_tool(model: str,memory_backend: Any = None,channel_backend: Any = None,+ app_config: Any = None,) -> Any:"""Instantiate a registry tool with its runtime dependencies."""@@ -256,7 +257,9 @@ def instantiate_registered_tool(return tool_cls(channel=channel_backend)if name == "llm":return tool_cls(engine=engine, model=model)- return tool_cls()+ from openjarvis.tools._paths import file_tool_kwargs++ return tool_cls(**file_tool_kwargs(name, app_config))def build_deep_research_tools(@@ -319,6 +322,7 @@ def resolve_agent_tools(mcp_tools: Iterable[Any] = (),mcp_clients: Iterable[Any] = (),knowledge_db_path: str | Path | None = None,+ app_config: Any = None,) -> ResolvedAgentTools:"""Resolve the effective live toolkit for a managed agent.@@ -397,6 +401,7 @@ def resolve_agent_tools(model=model,memory_backend=memory_backend,channel_backend=channel_backend,+ app_config=app_config,)except Exception as exc:logger.warning(@@ -444,6 +449,7 @@ def resolve_agent_tools(model=model,memory_backend=memory_backend,channel_backend=channel_backend,+ app_config=app_config,))except Exception as exc:diff --git a/src/openjarvis/cli/ask.py b/src/openjarvis/cli/ask.pyindex 8d8c5d4d..b5f2b0ed 100644--- a/src/openjarvis/cli/ask.py+++ b/src/openjarvis/cli/ask.py@@ -355,8 +355,10 @@ def _build_tools(tools.append(tool_cls(channel=channel))elif name == "llm":tools.append(tool_cls(engine=engine, model=model_name))- elif name == "file_read":- tools.append(tool_cls())+ elif name in {"file_read", "file_write"}:+ from openjarvis.tools._paths import file_tool_kwargs++ tools.append(tool_cls(**file_tool_kwargs(name, config)))else:tools.append(tool_cls())return toolsdiff --git a/src/openjarvis/cli/chat_cmd.py b/src/openjarvis/cli/chat_cmd.pyindex 493d80cd..9fa951af 100644--- a/src/openjarvis/cli/chat_cmd.py+++ b/src/openjarvis/cli/chat_cmd.py@@ -224,7 +224,11 @@ def chat(if isinstance(tcls, type) and issubclass(tcls, BaseTool):- tool_instances.append(tcls())+ from openjarvis.tools._paths import file_tool_kwargs++ tool_instances.append(+ tcls(**file_tool_kwargs(tname, config))+ )elif isinstance(tcls, BaseTool):tool_instances.append(tcls)if tool_instances:diff --git a/src/openjarvis/cli/serve.py b/src/openjarvis/cli/serve.pyindex ded1d5c5..950b279d 100644--- a/src/openjarvis/cli/serve.py+++ b/src/openjarvis/cli/serve.py@@ -351,7 +351,9 @@ def serve(if isinstance(tool_cls, type) and issubclass(tool_cls, BaseTool):- tools.append(tool_cls())+ from openjarvis.tools._paths import file_tool_kwargs++ tools.append(tool_cls(**file_tool_kwargs(name, config)))elif isinstance(tool_cls, BaseTool):tools.append(tool_cls)@@ -476,7 +478,11 @@ def serve(continue_tcls = ToolRegistry.get(_tname)if isinstance(_tcls, type) and issubclass(_tcls, BaseTool):- _channel_tools.append(_tcls())+ from openjarvis.tools._paths import file_tool_kwargs++ _channel_tools.append(+ _tcls(**file_tool_kwargs(_tname, config))+ )elif isinstance(_tcls, BaseTool):_channel_tools.append(_tcls)diff --git a/src/openjarvis/core/config.py b/src/openjarvis/core/config.pyindex fc425af7..31064215 100644--- a/src/openjarvis/core/config.py+++ b/src/openjarvis/core/config.py@@ -1449,6 +1449,8 @@ class SecurityConfig:local_engine_bypass: bool = Falselocal_tool_bypass: bool = Falseprofile: str = ""+ # Directories file_read/file_write may touch; empty means unrestricted.+ allowed_dirs: List[str] = field(default_factory=list)vault_key_path: str = field(default_factory=lambda: str(get_config_dir() / ".vault_key"))diff --git a/src/openjarvis/mcp/server.py b/src/openjarvis/mcp/server.pyindex ebac6460..193394f5 100644--- a/src/openjarvis/mcp/server.py+++ b/src/openjarvis/mcp/server.py@@ -62,6 +62,7 @@ class MCPServer:capability_policy: Optional[Any] = None,rate_limiter: Optional[Any] = None,agent_id: str = _MCP_AGENT_ID,+ allowed_dirs: Optional[List[str]] = None,) -> None:"""Create an MCP server with the same dispatch gates as other agents.@@ -71,9 +72,13 @@ class MCPServer:pass its policy and limiter here; ``ToolExecutor`` then applies bothdeclared and canonical built-in capability requirements before a toolcan run.++ ``allowed_dirs`` supplies the active configuration's filesystem policy+ to auto-discovered file tools; explicitly supplied tools keep their own+ constructor policy."""if tools is None:- tools = self._auto_discover_tools()+ tools = self._auto_discover_tools(allowed_dirs=allowed_dirs)self._tools: Dict[str, BaseTool] = {t.spec.name: t for t in tools}self._executor = ToolExecutor(tools,@@ -84,7 +89,9 @@ class MCPServer:)@staticmethod- def _auto_discover_tools() -> List[BaseTool]:+ def _auto_discover_tools(+ *, allowed_dirs: Optional[List[str]] = None+ ) -> List[BaseTool]:"""Auto-discover all built-in tools by direct import.Does not rely on ToolRegistry state — imports each tool class@@ -187,7 +194,10 @@ class MCPServer:for cls in _tool_classes:try:- tools.append(cls())+ if getattr(cls, "tool_id", None) in {"file_read", "file_write"}:+ tools.append(cls(allowed_dirs=allowed_dirs))+ else:+ tools.append(cls())except Exception as exc:logger.warning("Failed to instantiate tool from %r: %s", cls, exc)@@ -199,7 +209,12 @@ class MCPServer:for key in ToolRegistry.keys():if key not in known_names:try:- tool = ToolRegistry.create(key)+ kwargs = (+ {"allowed_dirs": allowed_dirs}+ if key in {"file_read", "file_write"}+ else {}+ )+ tool = ToolRegistry.create(key, **kwargs)if isinstance(tool, BaseTool):tools.append(tool)except Exception as exc:diff --git a/src/openjarvis/server/agent_manager_routes.py b/src/openjarvis/server/agent_manager_routes.pyindex 507011c6..26fccce9 100644--- a/src/openjarvis/server/agent_manager_routes.py+++ b/src/openjarvis/server/agent_manager_routes.py@@ -605,6 +605,7 @@ def _instantiate_managed_tool(model=model,memory_backend=memory_backend,channel_backend=channel_backend,+ app_config=getattr(app_state, "config", None),)@@ -959,6 +960,7 @@ async def _stream_managed_agent(mcp_tools=mcp_adapters.values(),mcp_clients=mcp_clients,knowledge_db_path=getattr(app_state, "knowledge_db_path", None),+ app_config=app_config,)# Load prior conversation context (DESC order, reverse for chronological).diff --git a/src/openjarvis/system/builder.py b/src/openjarvis/system/builder.pyindex fa29151a..a98574f7 100644--- a/src/openjarvis/system/builder.py+++ b/src/openjarvis/system/builder.py@@ -475,12 +475,14 @@ class SystemBuilder:):"""Resolve tool instances via MCPServer (primary) + external MCP servers."""from openjarvis.mcp.server import MCPServer+ from openjarvis.tools._paths import validate_allowed_dirsinternal_server = MCPServer(bus=bus,capability_policy=capability_policy,rate_limiter=rate_limiter,agent_id="system:mcp",+ allowed_dirs=validate_allowed_dirs(config.security.allowed_dirs),)for tool in internal_server.get_tools():self._inject_tool_deps(tool, engine, model, memory_backend, channel_backend)diff --git a/src/openjarvis/system/orchestrator.py b/src/openjarvis/system/orchestrator.pyindex b80f5b16..53fe73f0 100644--- a/src/openjarvis/system/orchestrator.py+++ b/src/openjarvis/system/orchestrator.py@@ -351,6 +351,14 @@ class QueryOrchestrator:from openjarvis.tools.llm_tool import LLMTooltools.append(LLMTool(s.engine, model=s.model))+ elif name in {"file_read", "file_write"} and ToolRegistry.contains(+ name+ ):+ from openjarvis.tools._paths import file_tool_kwargs++ tools.append(+ ToolRegistry.create(name, **file_tool_kwargs(name, s.config))+ )elif ToolRegistry.contains(name):tools.append(ToolRegistry.create(name))except Exception as exc:diff --git a/src/openjarvis/tools/_paths.py b/src/openjarvis/tools/_paths.pynew file mode 100644index 00000000..9f4f871c--- /dev/null+++ b/src/openjarvis/tools/_paths.py@@ -0,0 +1,38 @@+"""Default directory allow-list for the filesystem tools."""++from __future__ import annotations++import os+from typing import Any, List, Optional+++def validate_allowed_dirs(allowed_dirs: object) -> List[str]:+ """Validate an active policy without interpreting None as an ambient default."""+ if not isinstance(allowed_dirs, (list, tuple)) or any(+ not isinstance(directory, (str, os.PathLike))+ or not isinstance(os.fspath(directory), str)+ or not os.fspath(directory).strip()+ for directory in allowed_dirs+ ):+ raise ValueError("security.allowed_dirs must be a list of non-empty paths")+ return [os.fspath(directory) for directory in allowed_dirs]+++def file_tool_kwargs(name: str, config: Any = None) -> dict[str, List[str]]:+ """Bind native file tools to the caller's config when one was supplied."""+ if name not in {"file_read", "file_write"} or config is None:+ return {}+ return {"allowed_dirs": validate_allowed_dirs(config.security.allowed_dirs)}+++def resolve_allowed_dirs(allowed_dirs: Optional[List[str]]) -> List[str]:+ """Return *allowed_dirs*, or ``[security] allowed_dirs`` from the config.++ An explicit empty list keeps the historical unrestricted behaviour. Invalid+ or unreadable configuration must never silently remove a restriction.+ """+ if allowed_dirs is None:+ from openjarvis.core.config import load_config++ allowed_dirs = load_config().security.allowed_dirs+ return validate_allowed_dirs(allowed_dirs)diff --git a/src/openjarvis/tools/file_read.py b/src/openjarvis/tools/file_read.pyindex 59f6315a..b62db9f7 100644--- a/src/openjarvis/tools/file_read.py+++ b/src/openjarvis/tools/file_read.py@@ -7,6 +7,7 @@ from typing import Any, List, Optionalfrom openjarvis.core.registry import ToolRegistryfrom openjarvis.core.types import ToolResult+from openjarvis.tools._paths import resolve_allowed_dirsfrom openjarvis.tools._stubs import BaseTool, ToolSpec# Maximum file size to read (1 MB)@@ -23,7 +24,9 @@ class FileReadTool(BaseTool):self,allowed_dirs: Optional[List[str]] = None,) -> None:- self._allowed_dirs = [Path(d).resolve() for d in (allowed_dirs or [])]+ self._allowed_dirs = [+ Path(d).expanduser().resolve() for d in resolve_allowed_dirs(allowed_dirs)+ ]@propertydef spec(self) -> ToolSpec:@@ -65,6 +68,9 @@ class FileReadTool(BaseTool):success=False,)path = Path(file_path)+ if not path.is_absolute() and self._allowed_dirs:+ # A relative name means "inside the sandbox", not the process cwd.+ path = self._allowed_dirs[0] / path# Block sensitive files (secrets, credentials, keys)from openjarvis.security.file_policy import is_sensitive_filediff --git a/src/openjarvis/tools/file_write.py b/src/openjarvis/tools/file_write.pyindex 7369c344..4f9ebe8d 100644--- a/src/openjarvis/tools/file_write.py+++ b/src/openjarvis/tools/file_write.py@@ -7,6 +7,7 @@ from typing import Any, List, Optionalfrom openjarvis.core.registry import ToolRegistryfrom openjarvis.core.types import ToolResult+from openjarvis.tools._paths import resolve_allowed_dirsfrom openjarvis.tools._stubs import BaseTool, ToolSpec# Maximum file size to write (10 MB)@@ -23,7 +24,9 @@ class FileWriteTool(BaseTool):self,allowed_dirs: Optional[List[str]] = None,) -> None:- self._allowed_dirs = [Path(d).resolve() for d in (allowed_dirs or [])]+ self._allowed_dirs = [+ Path(d).expanduser().resolve() for d in resolve_allowed_dirs(allowed_dirs)+ ]@propertydef spec(self) -> ToolSpec:@@ -100,6 +103,9 @@ class FileWriteTool(BaseTool):create_dirs = params.get("create_dirs", False)path = Path(file_path)+ if not path.is_absolute() and self._allowed_dirs:+ # A relative name means "inside the sandbox", not the process cwd.+ path = self._allowed_dirs[0] / path# Block sensitive files (secrets, credentials, keys)from openjarvis.security.file_policy import is_sensitive_filediff --git a/tests/agents/test_executor_tools.py b/tests/agents/test_executor_tools.pyindex ea619351..bd896a5c 100644--- a/tests/agents/test_executor_tools.py+++ b/tests/agents/test_executor_tools.py@@ -171,6 +171,50 @@ def test_executor_handles_missing_tools(tmp_path):mgr.close()[email protected]("mode", ["tick", "ephemeral"])[email protected]("invalid_policy", [False, True])+def test_executor_file_tools_keep_application_directory_policy(+ tmp_path, monkeypatch, mode, invalid_policy+):+ from openjarvis.core.config import JarvisConfig+ from openjarvis.tools.file_read import FileReadTool++ cfg = JarvisConfig()+ cfg.security.allowed_dirs = None if invalid_policy else [str(tmp_path / "allowed")]+ monkeypatch.setattr("openjarvis.core.config.load_config", lambda: JarvisConfig())+ ToolRegistry.register_value("file_read", FileReadTool)+ AgentRegistry.register_value("monitor_operative", _CapturingToolAgent)+ _CapturingToolAgent.captured_tools = []+ system = FakeSystem(engine=FakeEngine([{"content": "unused"}]), config=cfg)+ mgr = AgentManager(db_path=str(tmp_path / "agents.db"))+ try:+ executor = AgentExecutor(manager=mgr, event_bus=EventBus(), system=system)+ if mode == "ephemeral":+ if invalid_policy:+ with pytest.raises(ValueError, match="allowed_dirs"):+ executor.run_ephemeral(+ "monitor_operative", "", "read", ["file_read"]+ )+ else:+ executor.run_ephemeral("monitor_operative", "", "read", ["file_read"])+ else:+ agent = mgr.create_agent(+ "file policy",+ agent_type="monitor_operative",+ config={"tools": ["file_read"], "instruction": "read"},+ )+ executor.execute_tick(agent["id"])+ tools = {tool.spec.name: tool for tool in _CapturingToolAgent.captured_tools}+ if invalid_policy:+ assert "file_read" not in tools+ else:+ outside = tmp_path / "outside.txt"+ outside.write_text("must stay outside")+ assert not tools["file_read"].execute(path=str(outside)).success+ finally:+ mgr.close()++def test_executor_handles_string_tools(tmp_path):"""Executor should handle comma-separated tool string as well as list."""_register_agent()diff --git a/tests/agents/test_tool_resolver.py b/tests/agents/test_tool_resolver.pyindex 0d640400..e58f1208 100644--- a/tests/agents/test_tool_resolver.py+++ b/tests/agents/test_tool_resolver.py@@ -152,6 +152,34 @@ def test_configured_tools_normalize_lists_and_comma_separated_strings(][email protected]("custom_spec", [False, True])[email protected]("invalid_policy", [False, True])+def test_managed_file_tools_use_application_policy(+ tmp_path, monkeypatch, custom_spec, invalid_policy+):+ from openjarvis.core.config import JarvisConfig+ from openjarvis.tools.file_read import FileReadTool++ cfg = JarvisConfig()+ cfg.security.allowed_dirs = None if invalid_policy else [str(tmp_path / "allowed")]+ monkeypatch.setattr("openjarvis.core.config.load_config", lambda: JarvisConfig())+ ToolRegistry.register_value("file_read", FileReadTool)+ entry = (+ {"type": "function", "function": {"name": "file_read"}}+ if custom_spec+ else "file_read"+ )+ resolved = tool_resolver.resolve_agent_tools(+ {"config": {"tools": [entry]}}, engine=None, model="", app_config=cfg+ )+ if invalid_policy:+ assert "file_read" not in resolved.by_name+ else:+ outside = tmp_path / "outside.txt"+ outside.write_text("must stay outside")+ assert not resolved.by_name["file_read"].execute(path=str(outside)).success++def test_registered_tool_advertisement_matches_to_openai_function(monkeypatch: pytest.MonkeyPatch,) -> None:diff --git a/tests/mcp/test_discovery.py b/tests/mcp/test_discovery.pyindex 76740952..7d3781b2 100644--- a/tests/mcp/test_discovery.py+++ b/tests/mcp/test_discovery.py@@ -222,6 +222,7 @@ def test_builder_wires_security_context_into_internal_mcp_server() -> None:from openjarvis.system import SystemBuilderconfig = JarvisConfig()+ config.security.allowed_dirs = ["/sandbox"]policy = object()limiter = object()bus = object()@@ -244,6 +245,7 @@ def test_builder_wires_security_context_into_internal_mcp_server() -> None:capability_policy=policy,rate_limiter=limiter,agent_id="system:mcp",+ allowed_dirs=["/sandbox"],)diff --git a/tests/server/test_managed_agent_resolved_tools.py b/tests/server/test_managed_agent_resolved_tools.pyindex 19857365..4b89dae3 100644--- a/tests/server/test_managed_agent_resolved_tools.py+++ b/tests/server/test_managed_agent_resolved_tools.py@@ -118,6 +118,47 @@ class _FinalOnlyEngine:yield StreamChunk(finish_reason="stop")+async def test_sse_file_tools_keep_application_directory_policy(tmp_path, monkeypatch):+ from openjarvis.core.config import JarvisConfig+ from openjarvis.server.agent_manager_routes import _stream_managed_agent+ from openjarvis.tools.file_read import FileReadTool++ cfg = JarvisConfig()+ cfg.security.allowed_dirs = [str(tmp_path / "allowed")]+ cfg.tools.storage.enabled = False+ monkeypatch.setattr("openjarvis.core.config.load_config", lambda: JarvisConfig())+ ToolRegistry.register_value("file_read", FileReadTool)+ outside = tmp_path / "outside.txt"+ outside.write_text("OUTSIDE_DIRECTORY_SENTINEL")+ engine = _ToolCallingEngine("file_read", {"path": str(outside)})+ manager = MagicMock()+ manager.list_messages.return_value = []+ response = await _stream_managed_agent(+ manager=manager,+ agent_record={+ "id": "restricted-agent",+ "name": "Restricted",+ "agent_type": "simple",+ "config": {+ "model": "test-model",+ "max_turns": 3,+ "tools": ["file_read"],+ "mcp_tools": False,+ },+ },+ user_content="Read the file",+ message_id="message-restricted",+ engine=engine,+ bus=None,+ app_state=SimpleNamespace(config=cfg, memory_backend=None),+ )+ async for _ in response.body_iterator:+ pass+ assert "outside allowed directories" in engine.observed_tool_result+ assert "OUTSIDE_DIRECTORY_SENTINEL" not in engine.observed_tool_result++class _SyntheticHttpSink(BaseTool):"""HTTP-shaped sink that records calls without performing network IO."""diff --git a/tests/tools/test_allowed_dirs_config.py b/tests/tools/test_allowed_dirs_config.pynew file mode 100644index 00000000..95844eb3--- /dev/null+++ b/tests/tools/test_allowed_dirs_config.py@@ -0,0 +1,231 @@+"""`[security] allowed_dirs` is the default directory allow-list for file tools."""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace+from unittest.mock import Mock++import pytest++from openjarvis.core.config import JarvisConfig, load_config+from openjarvis.tools._paths import resolve_allowed_dirs+from openjarvis.tools.file_read import FileReadTool+from openjarvis.tools.file_write import FileWriteTool+++def test_explicit_argument_wins(tmp_path: Path) -> None:+ assert resolve_allowed_dirs([str(tmp_path)]) == [str(tmp_path)]+++def test_explicit_empty_list_does_not_load_ambient_config(monkeypatch):+ monkeypatch.setattr(+ "openjarvis.core.config.load_config",+ Mock(side_effect=AssertionError("explicit policy must win")),+ )+ assert resolve_allowed_dirs([]) == []++[email protected]("tool_class", [FileReadTool, FileWriteTool])[email protected]("invalid", ["/tmp/allowed", [""], [None], {"/": True}, None])+def test_invalid_directory_config_never_creates_an_unrestricted_tool(+ monkeypatch, tool_class, invalid+):+ cfg = JarvisConfig()+ cfg.security.allowed_dirs = invalid+ monkeypatch.setattr("openjarvis.core.config.load_config", lambda: cfg)+ with pytest.raises(ValueError, match="allowed_dirs"):+ tool_class()++[email protected]("tool_class", [FileReadTool, FileWriteTool])+def test_unreadable_config_does_not_remove_directory_restrictions(+ monkeypatch, tool_class+):+ monkeypatch.setattr(+ "openjarvis.core.config.load_config",+ Mock(side_effect=PermissionError("configuration unavailable")),+ )+ with pytest.raises(PermissionError):+ tool_class()+++def test_scalar_toml_policy_is_rejected_instead_of_allowing_root(tmp_path, monkeypatch):+ config_path = tmp_path / "config.toml"+ config_path.write_text('[security]\nallowed_dirs = "/tmp/allowed"\n')+ monkeypatch.setenv("OPENJARVIS_CONFIG", str(config_path))+ with pytest.raises(ValueError, match="allowed_dirs"):+ FileReadTool()+++def test_config_default_is_empty() -> None:+ assert JarvisConfig().security.allowed_dirs == []+++def test_config_allowed_dirs_restricts_file_read(tmp_path, monkeypatch) -> None:+ inside = tmp_path / "ok"+ inside.mkdir()+ (inside / "a.txt").write_text("inside")+ outside = tmp_path / "outside.txt"+ outside.write_text("outside")++ cfg = JarvisConfig()+ cfg.security.allowed_dirs = [str(inside)]+ monkeypatch.setattr("openjarvis.core.config.load_config", lambda *a, **k: cfg)++ tool = FileReadTool()+ assert tool.execute(path=str(inside / "a.txt")).success+ assert not tool.execute(path=str(outside)).success+++def test_config_allowed_dirs_restricts_file_write(tmp_path, monkeypatch) -> None:+ inside = tmp_path / "ok"+ inside.mkdir()+ cfg = JarvisConfig()+ cfg.security.allowed_dirs = [str(inside)]+ monkeypatch.setattr("openjarvis.core.config.load_config", lambda *a, **k: cfg)++ tool = FileWriteTool()+ assert tool.execute(path=str(inside / "a.txt"), content="x").success+ assert not tool.execute(path=str(tmp_path / "b.txt"), content="x").success+++def test_relative_path_resolves_inside_first_allowed_dir(tmp_path: Path) -> None:+ box = tmp_path / "box"+ box.mkdir()+ write = FileWriteTool(allowed_dirs=[str(box)])+ assert write.execute(path="n.txt", content="hi").success+ assert (box / "n.txt").read_text() == "hi"+ read = FileReadTool(allowed_dirs=[str(box)])+ assert read.execute(path="n.txt").content == "hi"++[email protected]("entry_point", ["cli_sdk", "system", "orchestrator", "mcp"])+def test_active_config_controls_tools_instead_of_ambient_config(+ tmp_path, monkeypatch, entry_point+):+ from openjarvis.core.registry import ToolRegistry++ inside = tmp_path / "allowed"+ inside.mkdir()+ outside = tmp_path / "outside.txt"+ outside.write_text("outside must stay intact")+ config_path = tmp_path / "explicit.toml"+ config_path.write_text(+ f'[security]\nallowed_dirs = ["{inside.as_posix()}"]\n'+ '[tools]\nenabled = "file_read,file_write"\n'+ )+ cfg = load_config(config_path)+ ambient = JarvisConfig()+ monkeypatch.setattr("openjarvis.core.config.load_config", lambda *a, **kw: ambient)+ ToolRegistry.register_value("file_read", FileReadTool)+ ToolRegistry.register_value("file_write", FileWriteTool)++ if entry_point == "cli_sdk":+ from openjarvis.cli.ask import _build_tools++ tools = _build_tools(["file_read", "file_write"], cfg, None, "")+ elif entry_point == "system":+ from openjarvis.system.builder import SystemBuilder++ tools = SystemBuilder(config=cfg)._resolve_tools(cfg, None, "", None)+ elif entry_point == "orchestrator":+ from openjarvis.system.orchestrator import QueryOrchestrator++ system = SimpleNamespace(config=cfg, memory_backend=None, engine=None, model="")+ tools = QueryOrchestrator(system)._build_tools(["file_read", "file_write"])+ else:+ from openjarvis.mcp.server import MCPServer++ tools = MCPServer(allowed_dirs=cfg.security.allowed_dirs).get_tools()++ file_tools = {tool.spec.name: tool for tool in tools}+ read, write = file_tools["file_read"], file_tools["file_write"]+ assert write.execute(path="note.txt", content="allowed").success+ assert read.execute(path="note.txt").content == "allowed"+ assert not read.execute(path=str(outside)).success+ assert not write.execute(path=str(outside), content="blocked").success+ assert outside.read_text() == "outside must stay intact"++[email protected]("entry_point", ["cli_sdk", "system", "orchestrator"])+def test_invalid_active_policy_cannot_fall_back_to_valid_ambient_config(+ monkeypatch, entry_point+):+ from openjarvis.core.registry import ToolRegistry++ cfg = JarvisConfig()+ cfg.security.allowed_dirs = None+ cfg.tools.enabled = "file_read,file_write"+ ambient = JarvisConfig()+ monkeypatch.setattr("openjarvis.core.config.load_config", lambda: ambient)+ ToolRegistry.register_value("file_read", FileReadTool)+ ToolRegistry.register_value("file_write", FileWriteTool)+ if entry_point == "cli_sdk":+ from openjarvis.cli.ask import _build_tools++ with pytest.raises(ValueError, match="allowed_dirs"):+ _build_tools(["file_read", "file_write"], cfg, None, "")+ elif entry_point == "system":+ from openjarvis.system.builder import SystemBuilder++ with pytest.raises(ValueError, match="allowed_dirs"):+ SystemBuilder(config=cfg)._resolve_tools(cfg, None, "", None)+ else:+ from openjarvis.system.orchestrator import QueryOrchestrator++ system = SimpleNamespace(config=cfg, memory_backend=None, engine=None, model="")+ assert QueryOrchestrator(system)._build_tools(["file_read", "file_write"]) == []+++def test_managed_route_constructor_uses_active_policy(tmp_path, monkeypatch):+ from openjarvis.server.agent_manager_routes import _instantiate_managed_tool++ cfg = JarvisConfig()+ cfg.security.allowed_dirs = [str(tmp_path / "allowed")]+ state = SimpleNamespace(config=cfg, memory_backend=object())+ monkeypatch.setattr("openjarvis.core.config.load_config", lambda: JarvisConfig())+ outside = tmp_path / "outside.txt"+ outside.write_text("must stay outside")+ tool = _instantiate_managed_tool(+ FileReadTool, "file_read", engine=None, model="", app_state=state+ )+ assert not tool.execute(path=str(outside)).success+ cfg.security.allowed_dirs = None+ with pytest.raises(ValueError, match="allowed_dirs"):+ _instantiate_managed_tool(+ FileReadTool, "file_read", engine=None, model="", app_state=state+ )+++def test_traversal_and_symlinks_cannot_escape_configured_directory(tmp_path):+ inside = tmp_path / "allowed"+ inside.mkdir()+ outside = tmp_path / "outside"+ outside.mkdir()+ target = outside / "note.txt"+ target.write_text("keep")+ try:+ (inside / "link").symlink_to(outside, target_is_directory=True)+ except OSError:+ pytest.skip("Creating directory symlinks is not permitted on this host")+ read = FileReadTool(allowed_dirs=[str(inside)])+ write = FileWriteTool(allowed_dirs=[str(inside)])+ for path in ("../outside/note.txt", "link/note.txt"):+ assert not read.execute(path=path).success+ for mode in ("write", "append"):+ assert not write.execute(path=path, content="escape", mode=mode).success+ assert not write.execute(+ path="link/new/subdir/note.txt", content="escape", create_dirs=True+ ).success+ assert target.read_text() == "keep"+ assert not (outside / "new").exists()+++def test_configured_home_directory_is_expanded(tmp_path, monkeypatch):+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ (tmp_path / "allowed").mkdir()+ write = FileWriteTool(allowed_dirs=["~/allowed"])+ assert write.execute(path="note.txt", content="home").success+ assert (tmp_path / "allowed" / "note.txt").read_text() == "home"