Guard file handles and streamline scoped search

This commit is contained in:
Xubin Ren committed 2026-11-14 22:09:21 +08:00
1 parent 51884a244e
commit 5c7ff5b796
6 files changed
+137 -78

No files matched your search

-2
View File
@@ -131,8 +131,6 @@ class ApplyPatchTool(_WritableFsTool):
content = source.read_bytes().decode("utf-8")
except UnicodeDecodeError:
raise _PatchError(f"file is not UTF-8 text: {path}")
if action == "replace" and not source.is_file():
raise _PatchError(f"path to update is not a file: {path}")
elif action == "replace":
raise _PatchError(f"file to update does not exist: {path}")
originals[source] = content
+27 -38
View File
@@ -10,7 +10,6 @@ import threading
import time
from collections import Counter
from collections.abc import Callable
from contextlib import suppress
from dataclasses import dataclass
from functools import lru_cache
from itertools import count, islice
@@ -61,7 +60,6 @@ class _FindFilesEntry:
path: Path
rel_path: str
display_path: str
name: str
is_dir: bool
@@ -218,13 +216,6 @@ class _SearchTool(_FsTool):
def _ignore_directory(cls, name: str) -> bool:
return name in cls._IGNORE_DIRS or name.startswith(".verify-")
def _display_path(self, target: Path, root: Path) -> str:
workspace = self._files.display_workspace
if workspace:
with suppress(ValueError):
return target.relative_to(workspace).as_posix()
return target.relative_to(root).as_posix()
def _iter_files(self, tree: FileSearch, budget: _SearchBudget) -> Iterable[Path]:
if not tree.is_directory:
budget.visit_path()
@@ -318,21 +309,11 @@ class FindFilesTool(_SearchTool):
},
}
def _entry(self, path: Path, root: Path, *, is_dir: bool) -> _FindFilesEntry:
display_path = self._display_path(path, root)
return _FindFilesEntry(
path=path,
rel_path=path.relative_to(root).as_posix(),
display_path=display_path,
name=path.name,
is_dir=is_dir,
)
def _directory_entries(
self,
tree: FileSearch,
directory: Path,
root: Path,
entry_for: Callable[[Path, bool], _FindFilesEntry],
budget: _SearchBudget,
) -> Iterator[_FindFilesEntry]:
budget.checkpoint()
@@ -342,7 +323,7 @@ class FindFilesTool(_SearchTool):
is_dir = raw_entry.is_directory
if raw_entry.is_directory_link or (is_dir and self._ignore_directory(raw_entry.name)):
continue
yield self._entry(directory / raw_entry.name, root, is_dir=is_dir)
yield entry_for(directory / raw_entry.name, is_dir)
except OSError:
# os.walk silently skips directories that cannot be listed. Preserve
# that behavior while still allowing cancellation and budget errors
@@ -354,22 +335,23 @@ class FindFilesTool(_SearchTool):
tree: FileSearch,
*,
include_dirs: bool,
entry_for: Callable[[Path, bool], _FindFilesEntry],
budget: _SearchBudget,
) -> Iterable[_FindFilesEntry]:
budget.checkpoint()
root = tree.root
if not tree.is_directory:
budget.visit_path()
yield self._entry(root, root.parent, is_dir=False)
yield entry_for(root, False)
return
if include_dirs:
yield self._entry(root, root, is_dir=True)
yield entry_for(root, True)
sequence = count()
def queue(directory: Path) -> Iterator[tuple[str, int, _FindFilesEntry]]:
for entry in self._directory_entries(tree, directory, root, budget):
for entry in self._directory_entries(tree, directory, entry_for, budget):
sort_path = entry.display_path + ("/" if entry.is_dir else "")
yield sort_path, next(sequence), entry
@@ -391,6 +373,7 @@ class FindFilesTool(_SearchTool):
tree: FileSearch,
*,
include_dirs: bool,
entry_for: Callable[[Path, bool], _FindFilesEntry],
matches: Callable[[_FindFilesEntry], bool],
budget: _SearchBudget,
) -> Iterator[tuple[str, float]]:
@@ -399,7 +382,7 @@ class FindFilesTool(_SearchTool):
if not tree.is_directory or include_dirs:
if not tree.is_directory:
budget.visit_path()
entry = self._entry(root, root if tree.is_directory else root.parent, is_dir=tree.is_directory)
entry = entry_for(root, tree.is_directory)
if matches(entry):
yield entry.display_path + ("/" if entry.is_dir else ""), tree.modified(root)
if not tree.is_directory:
@@ -410,7 +393,7 @@ class FindFilesTool(_SearchTool):
while pending:
directory = pending.pop()
selected: list[_FindFilesEntry] = []
for entry in self._directory_entries(tree, directory, root, budget):
for entry in self._directory_entries(tree, directory, entry_for, budget):
if entry.is_dir:
pending.append(entry.path)
if not include_dirs:
@@ -419,7 +402,7 @@ class FindFilesTool(_SearchTool):
selected.append(entry)
if selected:
times = tree.modified_children(
directory, [entry.name for entry in selected], checkpoint=budget.checkpoint,
directory, [entry.path.name for entry in selected], checkpoint=budget.checkpoint,
)
for entry, mtime in zip(selected, times, strict=True):
yield entry.display_path + ("/" if entry.is_dir else ""), mtime
@@ -499,11 +482,19 @@ class FindFilesTool(_SearchTool):
)
terms = query.lower().split() if query else []
root = tree.root if tree.is_directory else tree.root.parent
workspace = self._files.display_workspace
display_root = workspace if workspace and root.is_relative_to(workspace) else root
def entry_for(path: Path, is_dir: bool) -> _FindFilesEntry:
rel_path = path.relative_to(root).as_posix()
displayed = rel_path if display_root == root else path.relative_to(display_root).as_posix()
return _FindFilesEntry(path, rel_path, displayed, is_dir)
def matches_entry(entry: _FindFilesEntry) -> bool:
if glob and not _match_glob(entry.rel_path, entry.name, glob):
if glob and not _match_glob(entry.rel_path, entry.path.name, glob):
return False
if file_type and (entry.is_dir or not _matches_type(entry.name, file_type)):
if file_type and (entry.is_dir or not _matches_type(entry.path.name, file_type)):
return False
if not terms:
return True
@@ -514,14 +505,14 @@ class FindFilesTool(_SearchTool):
try:
if sort == "modified":
by_modified = self._iter_modified(
tree, include_dirs=include_dirs, matches=matches_entry, budget=budget,
tree, include_dirs=include_dirs, entry_for=entry_for, matches=matches_entry, budget=budget,
)
matches = _ordered_prefix(by_modified, selection_size, key=lambda item: (-item[1], item[0]))
paths = [item[0] for item in matches]
else:
matching_paths = (
entry.display_path + ("/" if entry.is_dir else "")
for entry in self._iter_paths(tree, include_dirs=include_dirs, budget=budget)
for entry in self._iter_paths(tree, include_dirs=include_dirs, entry_for=entry_for, budget=budget)
if matches_entry(entry)
)
paths = list(islice(matching_paths, selection_size))
@@ -643,8 +634,8 @@ class GrepTool(_SearchTool):
}
@staticmethod
def _text_source(raw: bytes, max_bytes: int) -> DocumentLineSource | None:
if len(raw) > max_bytes or _is_binary(raw):
def _text_source(raw: bytes) -> DocumentLineSource | None:
if _is_binary(raw):
return None
try:
content = raw.decode("utf-8")
@@ -758,6 +749,7 @@ class GrepTool(_SearchTool):
)
workspace = self._files.display_workspace
display_root = workspace if workspace and root.is_relative_to(workspace) else root
with tree.search_bytes_reader() as read_bytes:
for file_path in self._iter_files(tree, budget):
rel_path = file_path.relative_to(root).as_posix()
@@ -765,10 +757,7 @@ class GrepTool(_SearchTool):
continue
if not _matches_type(file_path.name, type):
continue
display_path = rel_path
if workspace is not None and workspace != root:
with suppress(ValueError):
display_path = file_path.relative_to(workspace).as_posix()
display_path = rel_path if display_root == root else file_path.relative_to(display_root).as_posix()
source: DocumentLineSource | None = None
is_document = file_path.suffix.lower() in _DOCUMENT_EXTENSIONS
@@ -794,7 +783,7 @@ class GrepTool(_SearchTool):
skipped_large += 1
continue
mtime = contents.modified
source = self._text_source(contents.data, max_file_bytes)
source = self._text_source(contents.data)
if source is None:
skipped_binary += 1
continue
+43 -29
View File
@@ -6,7 +6,7 @@ import os
import re
import stat
from collections.abc import Callable, Generator, Iterable
from contextlib import AbstractContextManager, ExitStack, contextmanager
from contextlib import AbstractContextManager, ExitStack, contextmanager, suppress
from dataclasses import dataclass
from heapq import nsmallest
from operator import itemgetter
@@ -27,17 +27,17 @@ class NotRegularFileError(OSError):
@contextmanager
def _open_regular_file(
resolved_path: Path | str, *, dir_fd: int | None = None,
resolved_path: Path | str, *, dir_fd: int | None = None, write: bool = False,
) -> Generator[tuple[BinaryIO, int]]:
"""Own one descriptor for the entire read and report its initial size.
"""Own one descriptor and check its type before reading or truncating it.
Callers must supply an authorized path or a child of an authorized directory handle.
Where supported, refuse a swapped-in final symlink and avoid waiting on
a swapped-in FIFO. This does not protect ancestor path components.
"""
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
flags |= getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0)
with os.fdopen(os.open(resolved_path, flags, dir_fd=dir_fd), "rb") as stream:
flags = (os.O_WRONLY | os.O_CREAT) if write else os.O_RDONLY
flags |= getattr(os, "O_BINARY", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0)
with os.fdopen(os.open(resolved_path, flags, 0o666, dir_fd=dir_fd), "wb" if write else "rb") as stream:
opened = os.fstat(stream.fileno())
if not stat.S_ISREG(opened.st_mode):
raise NotRegularFileError
@@ -114,24 +114,22 @@ class WritableFile:
def exists(self) -> bool:
return self.path.exists()
def is_file(self) -> bool:
return self.path.is_file()
def size(self) -> int:
return self.path.stat().st_size
def read_bytes(self) -> bytes:
return self.path.read_bytes()
with _open_regular_file(self.path) as (stream, _):
return stream.read()
def write(self, content: str, *, create_parents: bool = False) -> None:
if create_parents:
self.path.parent.mkdir(parents=True, exist_ok=True)
self.path.write_text(content, encoding="utf-8", newline="")
_write_regular_file(self.path, content.encode("utf-8"))
def snapshot(self, max_bytes: int) -> FileSnapshot:
"""Read a bounded edit preview, not an independent path grant."""
try:
if not self.is_file():
if not self.path.is_file():
return FileSnapshot(exists=False, text="")
with _open_regular_file(self.path) as (stream, size):
if size > max_bytes:
@@ -148,6 +146,12 @@ class WritableFile:
return FileSnapshot(exists=True, text=text.replace("\r\n", "\n"))
def _write_regular_file(path: Path, data: bytes) -> None:
with _open_regular_file(path, write=True) as (stream, _):
stream.truncate(0)
stream.write(data)
def commit_file_edits(writes: dict[WritableFile, str]) -> None:
"""Write validated patch targets; restore their previous bytes on failure."""
backups = {target: target.read_bytes() if target.exists() else None for target in writes}
@@ -159,11 +163,13 @@ def commit_file_edits(writes: dict[WritableFile, str]) -> None:
except Exception:
for target in attempted:
data = backups[target]
if data is None:
target.path.unlink(missing_ok=True)
else:
target.path.parent.mkdir(parents=True, exist_ok=True)
target.path.write_bytes(data)
# A replaced target can reject rollback. Continue restoring the
# other targets without replacing the original write error.
with suppress(OSError):
if data is None:
target.path.unlink(missing_ok=True)
else:
_write_regular_file(target.path, data)
raise
@@ -326,15 +332,20 @@ class FileSearch:
opened_path = path.name
if size > limit:
return SearchBytes(None, modified)
with _open_regular_file(opened_path, dir_fd=fd) as (stream, opened_size):
if opened_size > limit:
return None
# Avoid allocating the full scan limit for each small file. The
# extra byte detects growth (including streams with a reported size of zero).
data = stream.read(opened_size + 1)
if len(data) > opened_size:
data += stream.read(limit + 1 - len(data))
return SearchBytes(data, modified)
try:
with _open_regular_file(opened_path, dir_fd=fd) as (stream, opened_size):
if opened_size > limit:
return SearchBytes(None, modified)
# The extra byte detects growth without allocating the full
# scan limit for every small file.
data = stream.read(opened_size + 1)
if len(data) > opened_size:
data += stream.read(limit + 1 - len(data))
return SearchBytes(data if len(data) <= limit else None, modified)
except OSError:
if not self.is_directory:
raise
return None # The file disappeared, changed type, or became unreadable.
@contextmanager
def search_bytes_reader(self) -> Generator[Callable[[Path, int], SearchBytes | None]]:
@@ -430,7 +441,7 @@ class WorkspaceFiles:
)
return access.project_path, self._allowed_root(access.allowed_root)
def _read_path(self, path: str | Path) -> Path:
def _read_path(self, path: str | Path, *, include_file_grants: bool = True) -> Path:
workspace, root = self._roots()
extra_roots: list[Path] = []
if root is not None:
@@ -445,7 +456,7 @@ class WorkspaceFiles:
workspace=workspace,
allowed_root=root,
extra_allowed_roots=extra_roots,
extra_allowed_files=self._read_files if root is not None else (),
extra_allowed_files=self._read_files if root is not None and include_file_grants else (),
)
def edit_target(self, path: str) -> WritableFile:
@@ -490,6 +501,7 @@ class WorkspaceFiles:
raise FileNotFoundError(path)
if not directory.is_dir():
raise NotADirectoryError(path)
directory = self._read_path(directory, include_file_grants=False)
tree = FileSearch(directory, True, self._read_path)
total = 0
@@ -526,6 +538,8 @@ class WorkspaceFiles:
def search_tree(self, path: str) -> FileSearch:
target = self._read_path(path)
mode = target.stat().st_mode
if not (stat.S_ISDIR(mode) or stat.S_ISREG(mode)):
if stat.S_ISDIR(mode):
target = self._read_path(target, include_file_grants=False)
elif not stat.S_ISREG(mode):
raise NotRegularFileError
return FileSearch(target, stat.S_ISDIR(mode), self._read_path)
+6 -7
View File
@@ -1,11 +1,11 @@
from __future__ import annotations
import asyncio
from pathlib import Path
import pytest
from nanobot.agent.tools.apply_patch import ApplyPatchTool
from nanobot.execution.files import WritableFile
def test_apply_patch_edits_replace(tmp_path):
@@ -472,18 +472,17 @@ def test_apply_patch_edits_rolls_back_when_later_write_fails(tmp_path, monkeypat
second_original = b"before\r\nsecond tail"
second.write_bytes(second_original)
tool = ApplyPatchTool(workspace=tmp_path)
write_text = Path.write_text
write = WritableFile.write
failed = False
def _fail_second_write(path, *args, **kwargs):
def _fail_second_write(target, *args, **kwargs):
nonlocal failed
written = write_text(path, *args, **kwargs)
if path == second and not failed:
write(target, *args, **kwargs)
if target.path == second.resolve() and not failed:
failed = True
raise OSError("injected second write failure")
return written
monkeypatch.setattr(Path, "write_text", _fail_second_write)
monkeypatch.setattr(WritableFile, "write", _fail_second_write)
result = asyncio.run(
tool.execute(
+34
View File
@@ -11,6 +11,7 @@ from nanobot.agent.tools.filesystem import (
ReadFileTool,
WriteFileTool,
)
from nanobot.execution.files import WorkspaceFiles
@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="requires a POSIX named pipe")
@@ -39,6 +40,39 @@ async def test_file_mutation_rejects_named_pipe_without_opening_it(tmp_path, mon
assert "Not a regular file: pipe" in result
@pytest.mark.skipif(not hasattr(os, "O_NOFOLLOW"), reason="requires no-follow file opens")
@pytest.mark.parametrize("operation", ["write", "patch"])
async def test_file_mutation_does_not_follow_a_symlink_swapped_in_after_authorization(
tmp_path, monkeypatch, operation,
):
workspace = (tmp_path / "workspace").resolve()
workspace.mkdir()
inside = workspace / "inside.txt"
outside = tmp_path / "private.txt"
inside.write_text("before", encoding="utf-8")
outside.write_text("private", encoding="utf-8")
authorize = WorkspaceFiles.edit_target
def swap_after_authorize(files, path):
target = authorize(files, path)
inside.unlink()
inside.symlink_to(outside)
return target
monkeypatch.setattr(WorkspaceFiles, "edit_target", swap_after_authorize)
if operation == "write":
result = await WriteFileTool(workspace=workspace, allowed_dir=workspace).execute(
path="inside.txt", content="changed",
)
else:
result = await ApplyPatchTool(workspace=workspace, allowed_dir=workspace).execute(
edits=[{"path": "inside.txt", "action": "add", "new_text": "changed"}],
)
assert result.is_error
assert outside.read_text(encoding="utf-8") == "private"
async def test_exact_edit_grant_does_not_list_sibling_files(tmp_path):
workspace = tmp_path / "workspace"
workspace.mkdir()
+27 -2
View File
@@ -21,7 +21,7 @@ from nanobot.agent.tools.search import FindFilesTool, GrepTool
from nanobot.agent.tools.web import WebSearchTool
from nanobot.bus.queue import MessageBus
from nanobot.config.schema import WebSearchConfig
from nanobot.execution.files import FileSearch
from nanobot.execution.files import FileSearch, WorkspaceFiles
from nanobot.providers.base import GenerationSettings
from nanobot.security.workspace_access import (
bind_workspace_scope,
@@ -363,6 +363,31 @@ async def test_exact_read_grant_does_not_authorize_a_directory_tree(tmp_path: Pa
assert "needle private" not in result
async def test_search_cannot_expand_exact_file_grant_after_file_becomes_directory(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
workspace = tmp_path / "workspace"
workspace.mkdir()
grant = tmp_path / "history.jsonl"
grant.write_text("needle history", encoding="utf-8")
resolve_read = WorkspaceFiles._read_path
def replace_after_grant(files, path, **kwargs):
target = resolve_read(files, path, **kwargs)
if target == grant.resolve() and target.is_file():
target.unlink()
target.mkdir()
(target / "private.txt").write_text("needle private", encoding="utf-8")
return target
monkeypatch.setattr(WorkspaceFiles, "_read_path", replace_after_grant)
tool = GrepTool(workspace=workspace, allowed_dir=workspace, extra_read_allowed_files=[grant])
result = await tool.execute(pattern="needle", path=str(grant))
assert is_tool_error_result(result)
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,
@@ -962,7 +987,7 @@ async def test_grep_keeps_read_limit_when_an_open_file_grows(tmp_path, monkeypat
if exceeds_limit:
assert result.startswith("No matches found")
assert "skipped 1 binary/unreadable files" in result
assert "skipped 1 large files" in result
else:
assert result == "growing.log"