From 5a234e8328e72ed99ca53b94ddd72ec8c59bd942 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:14:09 +0800 Subject: [PATCH] fix(tools): reject special files before file mutations --- nanobot/execution/files.py | 12 +++++++++-- tests/tools/test_filesystem_tools.py | 30 ++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/nanobot/execution/files.py b/nanobot/execution/files.py index b63f76e43..932cb2e3a 100644 --- a/nanobot/execution/files.py +++ b/nanobot/execution/files.py @@ -474,13 +474,21 @@ class WorkspaceFiles: def edit_target(self, path: str) -> WritableFile: workspace, root = self._roots() - return WritableFile(resolve_allowed_path( + target = resolve_allowed_path( path, workspace=workspace, allowed_root=root, extra_allowed_roots=self._write_dirs if root is not None else (), extra_allowed_files=self._write_files, - )) + ) + try: + mode = target.stat().st_mode + except FileNotFoundError: + pass # Write operations can create regular files. + else: + if not stat.S_ISREG(mode): + raise NotRegularFileError(f"Not a regular file: {path}") + return WritableFile(target) def read_file(self, path: str) -> ReadableFile: _reject_device(path) diff --git a/tests/tools/test_filesystem_tools.py b/tests/tools/test_filesystem_tools.py index cf11dcfdb..c8b59b371 100644 --- a/tests/tools/test_filesystem_tools.py +++ b/tests/tools/test_filesystem_tools.py @@ -1,5 +1,9 @@ +import os +from pathlib import Path + import pytest +from nanobot.agent.tools.apply_patch import ApplyPatchTool from nanobot.agent.tools.file_state import file_read_context from nanobot.agent.tools.filesystem import ( EditFileTool, @@ -9,6 +13,32 @@ from nanobot.agent.tools.filesystem import ( ) +@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="requires a POSIX named pipe") +@pytest.mark.parametrize("operation", ["write", "patch"]) +async def test_file_mutation_rejects_named_pipe_without_opening_it(tmp_path, monkeypatch, operation): + pipe = (tmp_path / "pipe").resolve() + os.mkfifo(pipe) + open_file = Path.open + + def reject_blocking_open(path, *args, **kwargs): + if path == pipe: + raise AssertionError("Opening a named pipe can block the agent") + return open_file(path, *args, **kwargs) + + monkeypatch.setattr(Path, "open", reject_blocking_open) + if operation == "write": + result = await WriteFileTool(workspace=tmp_path, allowed_dir=tmp_path).execute( + path="pipe", content="hello", + ) + else: + result = await ApplyPatchTool(workspace=tmp_path, allowed_dir=tmp_path).execute( + edits=[{"path": "pipe", "action": "add", "new_text": "hello"}], + ) + + assert result.is_error + assert "Not a regular file: pipe" in result + + async def test_exact_edit_grant_does_not_list_sibling_files(tmp_path): workspace = tmp_path / "workspace" workspace.mkdir()