fix(tools): preserve authorized document link search
This commit is contained in:
1 parent
d2e03d23a0
commit
66b8c447dc
5 files changed
+90
-56
No files matched your search
@@ -634,7 +634,7 @@ class GrepTool(_SearchTool):
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _open_source(source: ReadableFile, pages: str | None, max_bytes: int) -> DocumentLineSource | None:
|
def _open_source(source: ReadableFile, pages: str | None, max_bytes: int) -> DocumentLineSource | None:
|
||||||
if source.path.suffix.lower() in _DOCUMENT_EXTENSIONS:
|
if source.suffix in _DOCUMENT_EXTENSIONS:
|
||||||
return source.document_lines(pages=pages)
|
return source.document_lines(pages=pages)
|
||||||
with source.open() as (file, size):
|
with source.open() as (file, size):
|
||||||
if size > max_bytes:
|
if size > max_bytes:
|
||||||
@@ -770,7 +770,7 @@ class GrepTool(_SearchTool):
|
|||||||
skipped_large += 1
|
skipped_large += 1
|
||||||
continue
|
continue
|
||||||
source_iterator: Iterator[LocatedDocumentLine] | None = None
|
source_iterator: Iterator[LocatedDocumentLine] | None = None
|
||||||
is_document = file.path.suffix.lower() in _DOCUMENT_EXTENSIONS
|
is_document = file.suffix in _DOCUMENT_EXTENSIONS
|
||||||
try:
|
try:
|
||||||
source = self._open_source(file, pages, max_file_bytes)
|
source = self._open_source(file, pages, max_file_bytes)
|
||||||
if source is None:
|
if source is None:
|
||||||
|
|||||||
+10
-12
@@ -73,6 +73,7 @@ class ReadableFile:
|
|||||||
path: Path
|
path: Path
|
||||||
size: int
|
size: int
|
||||||
modified: float
|
modified: float
|
||||||
|
suffix: str
|
||||||
|
|
||||||
def open(self) -> AbstractContextManager[tuple[BinaryIO, int]]:
|
def open(self) -> AbstractContextManager[tuple[BinaryIO, int]]:
|
||||||
return _open_regular_file(self.path)
|
return _open_regular_file(self.path)
|
||||||
@@ -89,7 +90,7 @@ class ReadableFile:
|
|||||||
def document_lines(self, *, pages: str | None = None) -> DocumentLineSource | None:
|
def document_lines(self, *, pages: str | None = None) -> DocumentLineSource | None:
|
||||||
from nanobot.utils.document import open_document_line_source
|
from nanobot.utils.document import open_document_line_source
|
||||||
|
|
||||||
return open_document_line_source(self.path, pages=pages)
|
return open_document_line_source(self.path, pages=pages, suffix=self.suffix)
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
@@ -218,15 +219,15 @@ class FileSearch:
|
|||||||
return self._candidate(path).stat().st_mtime
|
return self._candidate(path).stat().st_mtime
|
||||||
|
|
||||||
def read_file(self, path: Path) -> ReadableFile:
|
def read_file(self, path: Path) -> ReadableFile:
|
||||||
return _regular_file(self._candidate(path))
|
return _regular_file(self._candidate(path), suffix=path.suffix.lower())
|
||||||
|
|
||||||
|
|
||||||
def _regular_file(target: Path) -> ReadableFile:
|
def _regular_file(target: Path, *, suffix: str | None = None) -> ReadableFile:
|
||||||
_reject_device(target, resolved=True)
|
_reject_device(target, resolved=True)
|
||||||
info = target.stat()
|
info = target.stat()
|
||||||
if not stat.S_ISREG(info.st_mode):
|
if not stat.S_ISREG(info.st_mode):
|
||||||
raise NotRegularFileError
|
raise NotRegularFileError
|
||||||
return ReadableFile(target, info.st_size, info.st_mtime)
|
return ReadableFile(target, info.st_size, info.st_mtime, target.suffix.lower() if suffix is None else suffix)
|
||||||
|
|
||||||
|
|
||||||
class WorkspaceFiles:
|
class WorkspaceFiles:
|
||||||
@@ -305,7 +306,7 @@ class WorkspaceFiles:
|
|||||||
)
|
)
|
||||||
return access.project_path, self._allowed_root(access.allowed_root)
|
return access.project_path, self._allowed_root(access.allowed_root)
|
||||||
|
|
||||||
def _read_path(self, path: str | Path, *, directory: bool = False) -> Path:
|
def _read_path(self, path: str | Path) -> Path:
|
||||||
workspace, root = self._roots()
|
workspace, root = self._roots()
|
||||||
extra_roots: list[Path] = []
|
extra_roots: list[Path] = []
|
||||||
if root is not None:
|
if root is not None:
|
||||||
@@ -320,7 +321,7 @@ class WorkspaceFiles:
|
|||||||
workspace=workspace,
|
workspace=workspace,
|
||||||
allowed_root=root,
|
allowed_root=root,
|
||||||
extra_allowed_roots=extra_roots,
|
extra_allowed_roots=extra_roots,
|
||||||
extra_allowed_files=self._read_files if root is not None and not directory else (),
|
extra_allowed_files=self._read_files if root is not None else (),
|
||||||
)
|
)
|
||||||
|
|
||||||
def edit_target(self, path: str) -> WritableFile:
|
def edit_target(self, path: str) -> WritableFile:
|
||||||
@@ -352,7 +353,7 @@ class WorkspaceFiles:
|
|||||||
def list_directory(
|
def list_directory(
|
||||||
self, path: str, *, recursive: bool, ignored: set[str], limit: int,
|
self, path: str, *, recursive: bool, ignored: set[str], limit: int,
|
||||||
) -> DirectoryListing:
|
) -> DirectoryListing:
|
||||||
directory = self._read_path(path, directory=True)
|
directory = self._read_path(path)
|
||||||
if not directory.exists():
|
if not directory.exists():
|
||||||
raise FileNotFoundError(path)
|
raise FileNotFoundError(path)
|
||||||
if not directory.is_dir():
|
if not directory.is_dir():
|
||||||
@@ -379,7 +380,7 @@ class WorkspaceFiles:
|
|||||||
def sibling_files(self, target: WritableFile) -> list[str]:
|
def sibling_files(self, target: WritableFile) -> list[str]:
|
||||||
"""Suggest names only when the caller can read the directory itself."""
|
"""Suggest names only when the caller can read the directory itself."""
|
||||||
try:
|
try:
|
||||||
parent = self._read_path(target.path.parent, directory=True)
|
parent = self._read_path(target.path.parent)
|
||||||
except PermissionError:
|
except PermissionError:
|
||||||
return []
|
return []
|
||||||
return [item.name for item in parent.iterdir() if item.is_file()] if parent.is_dir() else []
|
return [item.name for item in parent.iterdir() if item.is_file()] if parent.is_dir() else []
|
||||||
@@ -389,7 +390,4 @@ class WorkspaceFiles:
|
|||||||
mode = target.stat().st_mode
|
mode = target.stat().st_mode
|
||||||
if not (stat.S_ISDIR(mode) or stat.S_ISREG(mode)):
|
if not (stat.S_ISDIR(mode) or stat.S_ISREG(mode)):
|
||||||
raise NotRegularFileError
|
raise NotRegularFileError
|
||||||
is_directory = stat.S_ISDIR(mode)
|
return FileSearch(target, stat.S_ISDIR(mode), self._read_path)
|
||||||
if is_directory:
|
|
||||||
target = self._read_path(path, directory=True)
|
|
||||||
return FileSearch(target, is_directory, self._read_path)
|
|
||||||
@@ -70,7 +70,9 @@ def _is_path_exactly_allowed(
|
|||||||
except (OSError, RuntimeError, TypeError, ValueError):
|
except (OSError, RuntimeError, TypeError, ValueError):
|
||||||
continue
|
continue
|
||||||
if _path_key(allowed_file) == logical_key:
|
if _path_key(allowed_file) == logical_key:
|
||||||
return True
|
# A missing file can be created, but an exact file grant cannot
|
||||||
|
# become a directory grant if the path now refers to a directory.
|
||||||
|
return not resolved_path.is_dir()
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+44
-41
@@ -136,6 +136,7 @@ def open_document_line_source(
|
|||||||
path: str | Path,
|
path: str | Path,
|
||||||
*,
|
*,
|
||||||
pages: str | None = None,
|
pages: str | None = None,
|
||||||
|
suffix: str | None = None,
|
||||||
) -> DocumentLineSource | None:
|
) -> DocumentLineSource | None:
|
||||||
"""Open a document as an incremental stream of extracted lines.
|
"""Open a document as an incremental stream of extracted lines.
|
||||||
|
|
||||||
@@ -145,8 +146,9 @@ def open_document_line_source(
|
|||||||
blank separators) have ``searchable=False`` so range reads can retain them
|
blank separators) have ``searchable=False`` so range reads can retain them
|
||||||
without making grep match synthetic text.
|
without making grep match synthetic text.
|
||||||
"""
|
"""
|
||||||
|
# Format can come from a displayed name; all I/O uses the supplied path.
|
||||||
path = Path(path)
|
path = Path(path)
|
||||||
ext = path.suffix.lower()
|
ext = (path.suffix if suffix is None else suffix).lower()
|
||||||
if ext not in {".pdf", ".docx", ".xlsx", ".pptx"}:
|
if ext not in {".pdf", ".docx", ".xlsx", ".pptx"}:
|
||||||
return None
|
return None
|
||||||
if error := _extraction_path_error(path):
|
if error := _extraction_path_error(path):
|
||||||
@@ -241,54 +243,55 @@ def _open_xlsx_line_source(path: Path) -> DocumentLineSource:
|
|||||||
from openpyxl import load_workbook
|
from openpyxl import load_workbook
|
||||||
except ImportError as e:
|
except ImportError as e:
|
||||||
raise DocumentExtractionError("openpyxl not installed") from e
|
raise DocumentExtractionError("openpyxl not installed") from e
|
||||||
try:
|
|
||||||
workbook = load_workbook(path, read_only=True, data_only=True)
|
|
||||||
except Exception as e:
|
|
||||||
raise DocumentExtractionError(f"failed to open XLSX: {e!s}") from e
|
|
||||||
|
|
||||||
def iter_lines() -> Iterator[LocatedDocumentLine]:
|
def iter_lines() -> Iterator[LocatedDocumentLine]:
|
||||||
extracted_line = 0
|
# Let openpyxl parse the authorized file even if its real name has no suffix.
|
||||||
wrote_document_content = False
|
with path.open("rb") as source:
|
||||||
try:
|
try:
|
||||||
for worksheet in workbook.worksheets:
|
workbook = load_workbook(source, read_only=True, data_only=True)
|
||||||
sheet_name = worksheet.title
|
except Exception as e:
|
||||||
# Producer-supplied dimensions can omit cells that are present in the XML.
|
raise DocumentExtractionError(f"failed to open XLSX: {e!s}") from e
|
||||||
worksheet.reset_dimensions()
|
extracted_line = 0
|
||||||
wrote_header = False
|
wrote_document_content = False
|
||||||
for row_index, row in enumerate(worksheet.iter_rows(values_only=True), 1):
|
try:
|
||||||
cells = [str(cell) if cell is not None else "" for cell in row]
|
for worksheet in workbook.worksheets:
|
||||||
row_text = "\t".join(cells)
|
sheet_name = worksheet.title
|
||||||
if not row_text.strip():
|
# Producer-supplied dimensions can omit cells that are present in the XML.
|
||||||
continue
|
worksheet.reset_dimensions()
|
||||||
column_starts: list[int] = []
|
wrote_header = False
|
||||||
offset = 0
|
for row_index, row in enumerate(worksheet.iter_rows(values_only=True), 1):
|
||||||
for cell in cells:
|
cells = [str(cell) if cell is not None else "" for cell in row]
|
||||||
column_starts.append(offset)
|
row_text = "\t".join(cells)
|
||||||
offset += len(cell) + 1
|
if not row_text.strip():
|
||||||
if not wrote_header:
|
continue
|
||||||
if wrote_document_content:
|
column_starts: list[int] = []
|
||||||
|
offset = 0
|
||||||
|
for cell in cells:
|
||||||
|
column_starts.append(offset)
|
||||||
|
offset += len(cell) + 1
|
||||||
|
if not wrote_header:
|
||||||
|
if wrote_document_content:
|
||||||
|
extracted_line += 1
|
||||||
|
yield LocatedDocumentLine(
|
||||||
|
"", extracted_line, "", searchable=False
|
||||||
|
)
|
||||||
extracted_line += 1
|
extracted_line += 1
|
||||||
yield LocatedDocumentLine(
|
yield LocatedDocumentLine(
|
||||||
"", extracted_line, "", searchable=False
|
f"--- Sheet: {sheet_name} ---",
|
||||||
|
extracted_line,
|
||||||
|
"",
|
||||||
|
searchable=False,
|
||||||
)
|
)
|
||||||
|
wrote_header = True
|
||||||
|
wrote_document_content = True
|
||||||
extracted_line += 1
|
extracted_line += 1
|
||||||
yield LocatedDocumentLine(
|
yield LocatedDocumentLine(
|
||||||
f"--- Sheet: {sheet_name} ---",
|
row_text,
|
||||||
extracted_line,
|
extracted_line,
|
||||||
"",
|
f"sheet={sheet_name!r},row={row_index}",
|
||||||
searchable=False,
|
column_starts=tuple(column_starts),
|
||||||
)
|
)
|
||||||
wrote_header = True
|
finally:
|
||||||
wrote_document_content = True
|
workbook.close()
|
||||||
extracted_line += 1
|
|
||||||
yield LocatedDocumentLine(
|
|
||||||
row_text,
|
|
||||||
extracted_line,
|
|
||||||
f"sheet={sheet_name!r},row={row_index}",
|
|
||||||
column_starts=tuple(column_starts),
|
|
||||||
)
|
|
||||||
finally:
|
|
||||||
workbook.close()
|
|
||||||
|
|
||||||
return DocumentLineSource(iter_lines())
|
return DocumentLineSource(iter_lines())
|
||||||
|
|
||||||
|
|||||||
@@ -484,6 +484,37 @@ async def test_grep_searches_pdf_with_page_locator(tmp_path: Path) -> None:
|
|||||||
assert "pdf needle" in result
|
assert "pdf needle" in result
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(("suffix", "locator"), [
|
||||||
|
(".pdf", "[page=1,line=1]"),
|
||||||
|
(".xlsx", "[sheet='Sheet',row=1,cell=A1]"),
|
||||||
|
])
|
||||||
|
async def test_grep_uses_document_link_name_for_format(tmp_path: Path, suffix: str, locator: str) -> None:
|
||||||
|
target = tmp_path / "stored-content"
|
||||||
|
link = tmp_path / f"manual{suffix}"
|
||||||
|
if suffix == ".pdf":
|
||||||
|
import fitz
|
||||||
|
|
||||||
|
with fitz.open() as document:
|
||||||
|
document.new_page().insert_text((72, 72), "document needle")
|
||||||
|
document.save(target)
|
||||||
|
else:
|
||||||
|
from openpyxl import Workbook
|
||||||
|
|
||||||
|
workbook = Workbook()
|
||||||
|
workbook["Sheet"]["A1"] = "document needle"
|
||||||
|
workbook.save(target)
|
||||||
|
workbook.close()
|
||||||
|
try:
|
||||||
|
link.symlink_to(target)
|
||||||
|
except (NotImplementedError, OSError):
|
||||||
|
pytest.skip("symlinks unavailable")
|
||||||
|
|
||||||
|
tool = GrepTool(workspace=tmp_path, allowed_dir=tmp_path)
|
||||||
|
result = await tool.execute(pattern="document needle", path=".", glob=f"*{suffix}", fixed_strings=True)
|
||||||
|
assert f"{link.name}:2 {locator}" in result
|
||||||
|
assert "document needle" in result
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_grep_searches_xlsx_beyond_attachment_preview_limit(
|
async def test_grep_searches_xlsx_beyond_attachment_preview_limit(
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
|
|||||||
Reference in new issue
Block a user