refactor(tools): route file operations through scoped execution
This commit is contained in:
1 parent
c539da9269
commit
d2e03d23a0
16 files changed
+721
-513
No files matched your search
@@ -57,7 +57,7 @@ async def test_document_attachment_is_referenced_and_read_on_demand(
|
||||
media_dir.mkdir()
|
||||
csv_path = media_dir / "report.csv"
|
||||
csv_path.write_text("name,value\nnanobot,1", encoding="utf-8")
|
||||
monkeypatch.setattr("nanobot.agent.tools.path_utils.get_media_dir", lambda: media_dir)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
|
||||
|
||||
loop = _make_loop(
|
||||
workspace,
|
||||
|
||||
@@ -20,7 +20,11 @@ from nanobot.context_sources import (
|
||||
)
|
||||
from nanobot.llm_usage.context import llm_usage_source
|
||||
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
|
||||
from nanobot.security.workspace_access import build_workspace_scope
|
||||
from nanobot.security.workspace_access import (
|
||||
bind_workspace_scope,
|
||||
build_workspace_scope,
|
||||
reset_workspace_scope,
|
||||
)
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
|
||||
|
||||
@@ -217,8 +221,22 @@ async def test_subagent_keeps_project_runtime_scope_with_agent_owned_tools(tmp_p
|
||||
|
||||
spec = manager.runner.run.call_args.args[0]
|
||||
assert spec.workspace == project
|
||||
assert spec.tools.get("read_file")._workspace == agent_workspace.resolve()
|
||||
assert spec.tools.get("read_file")._restrict_to_workspace is True
|
||||
(project / "project.txt").write_text("project document", encoding="utf-8")
|
||||
(agent_workspace / "skills").mkdir()
|
||||
(agent_workspace / "skills" / "reference.txt").write_text("agent skill", encoding="utf-8")
|
||||
private = agent_workspace / "private.txt"
|
||||
private.write_text("agent private data", encoding="utf-8")
|
||||
token = bind_workspace_scope(build_workspace_scope(project, "restricted"))
|
||||
try:
|
||||
assert "project document" in await spec.tools.execute("read_file", {"path": "project.txt"})
|
||||
assert "agent skill" in await spec.tools.execute(
|
||||
"read_file", {"path": str(agent_workspace / "skills" / "reference.txt")},
|
||||
)
|
||||
denied = await spec.tools.execute("read_file", {"path": str(private)})
|
||||
assert denied.is_error
|
||||
assert "agent private data" not in denied
|
||||
finally:
|
||||
reset_workspace_scope(token)
|
||||
assert manager.tools_config.restrict_to_workspace is False
|
||||
|
||||
|
||||
|
||||
@@ -356,7 +356,7 @@ def test_apply_patch_media_dir_is_read_only_by_default(tmp_path, monkeypatch):
|
||||
media.mkdir()
|
||||
target = media / "demo.md"
|
||||
target.write_text("before\n", encoding="utf-8")
|
||||
monkeypatch.setattr("nanobot.agent.tools.path_utils.get_media_dir", lambda: media)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
|
||||
tool = ApplyPatchTool(workspace=workspace, allowed_dir=workspace)
|
||||
|
||||
result = asyncio.run(
|
||||
|
||||
@@ -9,6 +9,27 @@ from nanobot.agent.tools.filesystem import (
|
||||
)
|
||||
|
||||
|
||||
async def test_exact_edit_grant_does_not_list_sibling_files(tmp_path):
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
outside = tmp_path / "outside"
|
||||
outside.mkdir()
|
||||
target = outside / "approved.txt"
|
||||
(outside / "approved-secret.txt").write_text("private", encoding="utf-8")
|
||||
tool = EditFileTool(
|
||||
workspace=workspace, allowed_dir=workspace, extra_write_allowed_files=[target],
|
||||
)
|
||||
|
||||
missing = await tool.execute(path=str(target), old_text="old", new_text="new")
|
||||
assert "File not found" in missing
|
||||
assert "approved-secret.txt" not in missing
|
||||
assert not target.exists()
|
||||
|
||||
created = await tool.execute(path=str(target), old_text="", new_text="approved contents")
|
||||
assert not getattr(created, "is_error", False)
|
||||
assert target.read_text(encoding="utf-8") == "approved contents"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("newline", ["\n", "\r\n", "\r"])
|
||||
@pytest.mark.parametrize("operation", ["write", "edit_new", "edit_empty"])
|
||||
@@ -396,7 +417,7 @@ class TestWorkspaceRestriction:
|
||||
media_file = media_dir / "photo.txt"
|
||||
media_file.write_text("shared media", encoding="utf-8")
|
||||
|
||||
monkeypatch.setattr("nanobot.agent.tools.path_utils.get_media_dir", lambda: media_dir)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
|
||||
|
||||
tool = ReadFileTool(workspace=workspace, allowed_dir=workspace)
|
||||
result = await tool.execute(path=str(media_file))
|
||||
@@ -410,7 +431,7 @@ class TestWorkspaceRestriction:
|
||||
media_dir = tmp_path / "media"
|
||||
media_dir.mkdir()
|
||||
|
||||
monkeypatch.setattr("nanobot.agent.tools.path_utils.get_media_dir", lambda: media_dir)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
|
||||
|
||||
tool = WriteFileTool(workspace=workspace, allowed_dir=workspace)
|
||||
result = await tool.execute(path=str(media_dir / "hack.txt"), content="pwned")
|
||||
|
||||
@@ -110,7 +110,7 @@ class TestReadDedup:
|
||||
return self.stream.seek(*args)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.tools.filesystem.os.fdopen",
|
||||
"nanobot.execution.files.os.fdopen",
|
||||
lambda *args, **kwargs: CountingStream(real_fdopen(*args, **kwargs)),
|
||||
)
|
||||
visible = {} if case == "not_visible" else {"read-1": first}
|
||||
@@ -807,7 +807,7 @@ class TestBoundedTextReads:
|
||||
return chunk
|
||||
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.tools.filesystem.os.fdopen",
|
||||
"nanobot.execution.files.os.fdopen",
|
||||
lambda *args, **kwargs: GrowingStream(real_fdopen(*args, **kwargs)),
|
||||
)
|
||||
result = await tool.execute(path=str(f))
|
||||
@@ -886,7 +886,7 @@ class TestBoundedTextReads:
|
||||
return chunk
|
||||
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.tools.filesystem.os.fdopen",
|
||||
"nanobot.execution.files.os.fdopen",
|
||||
lambda *args, **kwargs: ChangeAfterPrecheck(real_fdopen(*args, **kwargs)),
|
||||
)
|
||||
with file_state.file_read_context("read-2", lambda: {"read-1": first}):
|
||||
@@ -932,7 +932,7 @@ class TestBoundedTextReads:
|
||||
return chunk
|
||||
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.tools.filesystem.os.fdopen",
|
||||
"nanobot.execution.files.os.fdopen",
|
||||
lambda *args, **kwargs: ChangeAfterPrecheck(real_fdopen(*args, **kwargs)),
|
||||
)
|
||||
tracemalloc.start()
|
||||
@@ -972,7 +972,7 @@ class TestBoundedTextReads:
|
||||
return chunk
|
||||
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.tools.filesystem.os.fdopen",
|
||||
"nanobot.execution.files.os.fdopen",
|
||||
lambda *args, **kwargs: GrowingStream(real_fdopen(*args, **kwargs)),
|
||||
)
|
||||
with file_state.file_read_context("read-2", lambda: {"read-1": first}):
|
||||
@@ -1013,7 +1013,7 @@ class TestBoundedTextReads:
|
||||
tool = ReadFileTool()
|
||||
try:
|
||||
with monkeypatch.context() as scoped:
|
||||
scoped.setattr("nanobot.agent.tools.filesystem.os.open", open_replacement)
|
||||
scoped.setattr("nanobot.execution.files.os.open", open_replacement)
|
||||
result = await tool.execute(path=str(f))
|
||||
finally:
|
||||
try:
|
||||
|
||||
@@ -186,6 +186,47 @@ async def test_find_files_scan_keeps_event_loop_responsive(
|
||||
assert await asyncio.wait_for(task, timeout=0.5) == "match.txt"
|
||||
|
||||
|
||||
async def test_grep_authorizes_the_targets_of_links_found_during_traversal(tmp_path: Path):
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
inside = workspace / "inside.txt"
|
||||
inside.write_text("needle allowed", encoding="utf-8")
|
||||
outside = tmp_path / "outside.txt"
|
||||
outside.write_text("needle outside contents", encoding="utf-8")
|
||||
try:
|
||||
(workspace / "inside-link.txt").symlink_to(inside)
|
||||
(workspace / "outside-link.txt").symlink_to(outside)
|
||||
except (NotImplementedError, OSError):
|
||||
pytest.skip("symlinks unavailable")
|
||||
|
||||
tool = GrepTool(workspace=workspace, allowed_dir=workspace)
|
||||
result = await tool.execute(pattern="needle", fixed_strings=True)
|
||||
assert "inside-link.txt" in result
|
||||
assert "needle allowed" in result
|
||||
assert "needle outside contents" not in result
|
||||
|
||||
|
||||
async def test_exact_read_grant_does_not_authorize_a_directory_tree(tmp_path: Path):
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
grant = tmp_path / "history.jsonl"
|
||||
options = {
|
||||
"workspace": workspace,
|
||||
"allowed_dir": workspace,
|
||||
"extra_read_allowed_files": [grant],
|
||||
}
|
||||
grant.write_text("needle history", encoding="utf-8")
|
||||
grep = GrepTool(**options)
|
||||
assert "needle history" in await grep.execute(pattern="needle", path=str(grant))
|
||||
|
||||
grant.unlink()
|
||||
grant.mkdir()
|
||||
(grant / "private.txt").write_text("needle private", encoding="utf-8")
|
||||
result = await grep.execute(pattern="needle", path=str(grant))
|
||||
assert "outside allowed directory" in result
|
||||
assert "needle private" not in result
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_find_files_cancellation_stops_worker_scan(
|
||||
tmp_path: Path,
|
||||
@@ -226,12 +267,12 @@ async def test_find_files_path_limit_stops_after_pagination_lookahead(
|
||||
tool = FindFilesTool(workspace=tmp_path, allowed_dir=tmp_path)
|
||||
visited: list[str] = []
|
||||
|
||||
def ordered_iter_paths(root: Path, *, include_dirs: bool, budget):
|
||||
def ordered_iter_paths(tree, *, include_dirs: bool, budget):
|
||||
del include_dirs
|
||||
for path in paths:
|
||||
budget.checkpoint()
|
||||
visited.append(path.name)
|
||||
yield tool._entry(path, root, is_dir=False)
|
||||
yield tool._entry(path, tree.root, is_dir=False)
|
||||
|
||||
monkeypatch.setattr(tool, "_iter_paths", ordered_iter_paths)
|
||||
result = await tool.execute(path=".", head_limit=1)
|
||||
@@ -982,13 +1023,13 @@ async def test_grep_scan_yields_and_cancellation_stops_worker(tmp_path, monkeypa
|
||||
tool = GrepTool(workspace=tmp_path)
|
||||
started, stopped = threading.Event(), threading.Event()
|
||||
|
||||
def blocking_iter_files(root, budget):
|
||||
def blocking_iter_files(tree, budget):
|
||||
started.set()
|
||||
try:
|
||||
if not budget.cancelled.wait(timeout=2):
|
||||
raise TimeoutError("worker did not receive cancellation")
|
||||
budget.checkpoint()
|
||||
yield root / "unreachable.txt"
|
||||
yield tree.root / "unreachable.txt"
|
||||
finally:
|
||||
stopped.set()
|
||||
|
||||
@@ -1061,7 +1102,7 @@ async def test_grep_closes_document_stream_and_preserves_locators(tmp_path, monk
|
||||
closed.append(True)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.tools.search.open_document_line_source",
|
||||
"nanobot.utils.document.open_document_line_source",
|
||||
lambda *_args, **_kwargs: DocumentLineSource(document_lines(), "pages=2-3"),
|
||||
)
|
||||
result = await GrepTool(workspace=tmp_path).execute(
|
||||
|
||||
@@ -2,10 +2,11 @@ from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
from dataclasses import fields
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.tools.base import Tool
|
||||
from nanobot.agent.tools.context import ToolContext
|
||||
from nanobot.agent.tools.loader import _SKIP_MODULES, ToolLoader
|
||||
@@ -184,35 +185,25 @@ def test_loader_preserves_caller_supplied_tool(tmp_path):
|
||||
assert "read_file" not in registered
|
||||
|
||||
|
||||
def test_fs_tool_create_builds_from_context():
|
||||
@pytest.mark.parametrize(("restrict", "sandbox"), [(False, ""), (True, ""), (False, "bwrap")])
|
||||
async def test_fs_tool_create_uses_context_workspace_and_restrictions(tmp_path, restrict, sandbox):
|
||||
from nanobot.agent.tools.filesystem import ReadFileTool
|
||||
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
(workspace / "inside.txt").write_text("inside", encoding="utf-8")
|
||||
(tmp_path / "outside.txt").write_text("outside contents", encoding="utf-8")
|
||||
mock_config = MagicMock()
|
||||
mock_config.restrict_to_workspace = False
|
||||
mock_config.exec.sandbox = ""
|
||||
ctx = ToolContext(config=mock_config, workspace="/tmp/test")
|
||||
tool = ReadFileTool.create(ctx)
|
||||
assert isinstance(tool, ReadFileTool)
|
||||
assert tool._workspace == Path("/tmp/test")
|
||||
|
||||
|
||||
def test_fs_tool_create_respects_restrict_to_workspace():
|
||||
from nanobot.agent.tools.filesystem import ReadFileTool
|
||||
mock_config = MagicMock()
|
||||
mock_config.restrict_to_workspace = True
|
||||
mock_config.exec.sandbox = ""
|
||||
ctx = ToolContext(config=mock_config, workspace="/tmp/test")
|
||||
tool = ReadFileTool.create(ctx)
|
||||
assert tool._allowed_dir == Path("/tmp/test")
|
||||
|
||||
|
||||
def test_fs_tool_create_respects_sandbox():
|
||||
from nanobot.agent.tools.filesystem import ReadFileTool
|
||||
mock_config = MagicMock()
|
||||
mock_config.restrict_to_workspace = False
|
||||
mock_config.exec.sandbox = "bwrap"
|
||||
ctx = ToolContext(config=mock_config, workspace="/tmp/test")
|
||||
tool = ReadFileTool.create(ctx)
|
||||
assert tool._allowed_dir == Path("/tmp/test")
|
||||
mock_config.restrict_to_workspace = restrict
|
||||
mock_config.exec.sandbox = sandbox
|
||||
tool = ReadFileTool.create(ToolContext(config=mock_config, workspace=str(workspace)))
|
||||
assert "inside" in await tool.execute(path="inside.txt")
|
||||
outside = await tool.execute(path="../outside.txt")
|
||||
if restrict or sandbox:
|
||||
assert outside.is_error
|
||||
assert "outside contents" not in outside
|
||||
else:
|
||||
assert "outside contents" in outside
|
||||
|
||||
|
||||
async def test_message_tool_create():
|
||||
|
||||
@@ -15,7 +15,6 @@ from nanobot.utils.file_edit_events import (
|
||||
build_file_edit_start_event,
|
||||
build_unified_diff_payload,
|
||||
prepare_file_edit_trackers,
|
||||
read_file_snapshot,
|
||||
)
|
||||
|
||||
|
||||
@@ -245,7 +244,7 @@ def test_binary_file_is_reported_but_not_counted(tmp_path: Path) -> None:
|
||||
params={"path": "data.bin", "old_text": "before", "new_text": "after"},
|
||||
)
|
||||
[tracker] = trackers
|
||||
assert not read_file_snapshot(target).countable
|
||||
assert not tracker.before.countable
|
||||
target.write_bytes(b"\x00\x01after")
|
||||
event = build_file_edit_end_event(tracker)
|
||||
assert event["binary"] is True
|
||||
@@ -371,3 +370,17 @@ def test_untracked_tools_do_not_prepare_file_edit_trackers(tmp_path: Path) -> No
|
||||
workspace=tmp_path,
|
||||
params={"path": "created-by-shell.txt"},
|
||||
) == []
|
||||
|
||||
|
||||
def test_edit_progress_does_not_snapshot_a_denied_target(tmp_path: Path) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
(tmp_path / "outside.txt").write_text("private", encoding="utf-8")
|
||||
tool = WriteFileTool(workspace=workspace, allowed_dir=workspace)
|
||||
assert prepare_file_edit_trackers(
|
||||
call_id="denied",
|
||||
tool_name="write_file",
|
||||
tool=tool,
|
||||
workspace=workspace,
|
||||
params={"path": "../outside.txt", "content": "new"},
|
||||
) == []
|
||||
Reference in new issue
Block a user