file_read tool crashes with a raw ValueError instead of a descriptive ExecutionError when the path contains an embedded NUL byte #180

Closed
opened 2026-11-20 09:46:43 +00:00 by CoreRasurae · 1 comment
Member

Metadata

Commit Message: fix(agents): reject file_read path arguments containing an embedded NUL byte before touching the filesystem
Branch: bugfix/m1-file-read-nul-byte-path

Background and context

ToolAgent._file_read_tool (src/cleveractors/agents/tool.py) validates the file argument for emptiness, for shell-command-like syntax (pipe/redirect/semicolon characters and known shell command names), and — only when safe_mode is enabled — for .. traversal, a leading /, and (via SandboxRootPolicy) a symlink-escape check that calls os.path.realpath(filepath) directly (no try/except around it, at the line implementing the ADR-2035 D-4 symlink-escape closure). None of these checks reject a file string containing an embedded NUL byte (\x00) before it reaches that os.path.realpath() call. CPython's os module raises a raw ValueError ("embedded null character"/"embedded null byte" in path) for any path argument containing a NUL byte, and this happens below the tool's own validation layer and before _file_read_tool's own try/except block (which only wraps the later os.path.isdir/file-read logic and only catches FileNotFoundError, OSError, and UnicodeDecodeError) is even entered.

This is the same defect class reported in #175 for file_write (a corrupted/malformed file argument sails through path validation and only fails deep inside a filesystem call) — discovered while auditing file_read, shell, and python_exec for the same class of defect, at the maintainer's request, following up on #175/#176/PR #178.

Current behavior

Confirmed directly against this branch by invoking the tool programmatically:

await tool_agent.invoke("file_read", {"file": "abc\x00def.txt"})

raises:

ValueError: lstat: embedded null character in path

This propagates uncaught out of _file_read_tool and _execute_tool. When the tool agent is driven through ToolAgent.invoke() — the graph-node dispatch entry point documented in its own docstring as "Path B" — there is no surrounding catch-all at all, so the raw ValueError reaches the caller directly instead of the agent's ExecutionError contract. When driven instead through process_message(), the outer generic except Exception as e there does catch it and re-wraps it as ExecutionError(f"Tool execution failed: {str(e)}") — but the resulting message is still just Python's raw, low-level text ("Tool execution failed: lstat: embedded null character in path"), with no indication of which character was invalid or that this was a validation failure rather than a filesystem failure.

Expected behavior

_file_read_tool rejects a file argument containing a NUL byte (or other ASCII control character illegal in a filename) with a descriptive ExecutionError, raised before any call that touches the filesystem (os.path.realpath, os.path.isdir, the shared file-read core). The behavior must be identical regardless of which public entry point (invoke() or process_message()) dispatches the call — a raw ValueError must never reach either caller.

Acceptance criteria

  • A file_read call whose file argument contains an embedded NUL byte (\x00) or another ASCII control character (\x01-\x1F) is rejected with an ExecutionError before os.path.realpath, os.path.isdir, or any other OS call is reached.
  • The rejection happens identically whether file_read is dispatched via ToolAgent.invoke() or ToolAgent.process_message() — no raw ValueError reaches either caller.
  • The raised ExecutionError message names the specific problem found (e.g. an embedded NUL byte or control character), not a propagated low-level ValueError/OSError string.
  • Legitimate relative and absolute (in unsafe mode) paths — including ones with spaces, hyphens, underscores, dots within a segment, and nested subdirectories — continue to be accepted unchanged, with no regression.
  • The existing shell-command-detection, traversal, absolute-path, and symlink-escape checks in _file_read_tool continue to pass unchanged.

Supporting information

  • Affected method: ToolAgent._file_read_tool in src/cleveractors/agents/tool.py. Crash site: the unguarded os.path.realpath(filepath) call reached by the safe_mode symlink-escape branch, which executes before _file_read_tool's own try block begins.
  • Related but distinct: #175 (the analogous defect in file_write's _validate_file_path_safety, which only checks for traversal/absolute-path/home-directory escapes, not well-formedness). _validate_file_path_safety has an equally unguarded os.path.realpath() call at its own symlink-escape check and is equally susceptible to the embedded-NUL-byte crash described here; since #175's own subtasks already call for extending its path-validation fix to "file_write, and any sibling tools such as file_read", whichever of these two issues lands second should factor the character/well-formedness check into one shared helper so the two call sites cannot drift apart.
  • Not overlapping with #126 / #105 (symlink-safe open / TOCTOU hardening) — those address a different, already-solved concern (race-safe resolution), not malformed-input rejection.

Subtasks

  • Add a path-character/well-formedness check to _file_read_tool (or a helper shared with _validate_file_path_safety) that rejects an embedded NUL byte and other filename-illegal control characters, raising a descriptive ExecutionError, before any filesystem call.
  • Ensure the check runs ahead of every code path inside _file_read_tool that can reach os.path.realpath/os.path.isdir, including both the safe_mode symlink-escape branch and the main directory-listing/file-read path.
  • Tests (Behave): add scenarios in features/ covering a file_read path with an embedded NUL byte and a path with another illegal control character, confirming the failure is an ExecutionError (not a raw ValueError) from both the invoke() and process_message() entry points, and confirming valid paths remain unaffected.
  • Verify coverage >=97% via nox -s coverage_report.
  • Run nox (all default sessions), fix any errors.

Definition of Done

This issue is complete when:

  • All subtasks above are completed and checked off.
  • A Git commit is created where the first line matches the Commit Message in Metadata exactly.
  • The commit is pushed to the branch matching the Branch in Metadata exactly.
  • The commit is submitted as a PR to master, reviewed, and merged.
  • A companion Type/Testing TDD issue exists, the TDD scenario (tagged @tdd_expected_fail) is merged first, and this issue's Forgejo dependency correctly shows it depends on that TDD issue.

Note for triage

This fits Epic #77 ("LLM Agent Runtime Stabilization") as a tool-dispatch input-validation hardening item, directly alongside its sibling #175 (same defect class, file_write) — recommend linking it there, but leaving the final call, milestone assignment, and MoSCoW to maintainer/project-owner triage.

## Metadata Commit Message: `fix(agents): reject file_read path arguments containing an embedded NUL byte before touching the filesystem` Branch: bugfix/m1-file-read-nul-byte-path ## Background and context `ToolAgent._file_read_tool` (`src/cleveractors/agents/tool.py`) validates the `file` argument for emptiness, for shell-command-like syntax (pipe/redirect/semicolon characters and known shell command names), and — only when `safe_mode` is enabled — for `..` traversal, a leading `/`, and (via `SandboxRootPolicy`) a symlink-escape check that calls `os.path.realpath(filepath)` directly (no `try`/`except` around it, at the line implementing the ADR-2035 D-4 symlink-escape closure). None of these checks reject a `file` string containing an embedded NUL byte (`\x00`) before it reaches that `os.path.realpath()` call. CPython's `os` module raises a raw `ValueError` ("embedded null character"/"embedded null byte" in path) for any path argument containing a NUL byte, and this happens below the tool's own validation layer and before `_file_read_tool`'s own `try`/`except` block (which only wraps the later `os.path.isdir`/file-read logic and only catches `FileNotFoundError`, `OSError`, and `UnicodeDecodeError`) is even entered. This is the same defect class reported in #175 for `file_write` (a corrupted/malformed `file` argument sails through path validation and only fails deep inside a filesystem call) — discovered while auditing `file_read`, `shell`, and `python_exec` for the same class of defect, at the maintainer's request, following up on #175/#176/PR #178. ## Current behavior Confirmed directly against this branch by invoking the tool programmatically: ```python await tool_agent.invoke("file_read", {"file": "abc\x00def.txt"}) ``` raises: ``` ValueError: lstat: embedded null character in path ``` This propagates uncaught out of `_file_read_tool` and `_execute_tool`. When the tool agent is driven through `ToolAgent.invoke()` — the graph-node dispatch entry point documented in its own docstring as "Path B" — there is no surrounding catch-all at all, so the raw `ValueError` reaches the caller directly instead of the agent's `ExecutionError` contract. When driven instead through `process_message()`, the outer generic `except Exception as e` there does catch it and re-wraps it as `ExecutionError(f"Tool execution failed: {str(e)}")` — but the resulting message is still just Python's raw, low-level text ("Tool execution failed: lstat: embedded null character in path"), with no indication of which character was invalid or that this was a validation failure rather than a filesystem failure. ## Expected behavior `_file_read_tool` rejects a `file` argument containing a NUL byte (or other ASCII control character illegal in a filename) with a descriptive `ExecutionError`, raised before any call that touches the filesystem (`os.path.realpath`, `os.path.isdir`, the shared file-read core). The behavior must be identical regardless of which public entry point (`invoke()` or `process_message()`) dispatches the call — a raw `ValueError` must never reach either caller. ## Acceptance criteria - A `file_read` call whose `file` argument contains an embedded NUL byte (`\x00`) or another ASCII control character (`\x01`-`\x1F`) is rejected with an `ExecutionError` **before** `os.path.realpath`, `os.path.isdir`, or any other OS call is reached. - The rejection happens identically whether `file_read` is dispatched via `ToolAgent.invoke()` or `ToolAgent.process_message()` — no raw `ValueError` reaches either caller. - The raised `ExecutionError` message names the specific problem found (e.g. an embedded NUL byte or control character), not a propagated low-level `ValueError`/`OSError` string. - Legitimate relative and absolute (in unsafe mode) paths — including ones with spaces, hyphens, underscores, dots within a segment, and nested subdirectories — continue to be accepted unchanged, with no regression. - The existing shell-command-detection, traversal, absolute-path, and symlink-escape checks in `_file_read_tool` continue to pass unchanged. ## Supporting information - Affected method: `ToolAgent._file_read_tool` in `src/cleveractors/agents/tool.py`. Crash site: the unguarded `os.path.realpath(filepath)` call reached by the `safe_mode` symlink-escape branch, which executes before `_file_read_tool`'s own `try` block begins. - Related but distinct: #175 (the analogous defect in `file_write`'s `_validate_file_path_safety`, which only checks for traversal/absolute-path/home-directory escapes, not well-formedness). `_validate_file_path_safety` has an equally unguarded `os.path.realpath()` call at its own symlink-escape check and is equally susceptible to the embedded-NUL-byte crash described here; since #175's own subtasks already call for extending its path-validation fix to "file_write, and any sibling tools such as file_read", whichever of these two issues lands second should factor the character/well-formedness check into one shared helper so the two call sites cannot drift apart. - Not overlapping with #126 / #105 (symlink-safe `open` / TOCTOU hardening) — those address a different, already-solved concern (race-safe resolution), not malformed-input rejection. ## Subtasks - [ ] Add a path-character/well-formedness check to `_file_read_tool` (or a helper shared with `_validate_file_path_safety`) that rejects an embedded NUL byte and other filename-illegal control characters, raising a descriptive `ExecutionError`, before any filesystem call. - [ ] Ensure the check runs ahead of every code path inside `_file_read_tool` that can reach `os.path.realpath`/`os.path.isdir`, including both the `safe_mode` symlink-escape branch and the main directory-listing/file-read path. - [ ] Tests (Behave): add scenarios in `features/` covering a `file_read` path with an embedded NUL byte and a path with another illegal control character, confirming the failure is an `ExecutionError` (not a raw `ValueError`) from both the `invoke()` and `process_message()` entry points, and confirming valid paths remain unaffected. - [ ] Verify coverage >=97% via `nox -s coverage_report`. - [ ] Run `nox` (all default sessions), fix any errors. ## Definition of Done This issue is complete when: - All subtasks above are completed and checked off. - A Git commit is created where the first line matches the Commit Message in Metadata exactly. - The commit is pushed to the branch matching the Branch in Metadata exactly. - The commit is submitted as a PR to master, reviewed, and merged. - A companion `Type/Testing` TDD issue exists, the TDD scenario (tagged `@tdd_expected_fail`) is merged first, and this issue's Forgejo dependency correctly shows it depends on that TDD issue. ## Note for triage This fits Epic #77 ("LLM Agent Runtime Stabilization") as a tool-dispatch input-validation hardening item, directly alongside its sibling #175 (same defect class, `file_write`) — recommend linking it there, but leaving the final call, milestone assignment, and MoSCoW to maintainer/project-owner triage.
Author
Member

The problem described in this issue has already been addressed when handling issue #175

The problem described in this issue has already been addressed when handling issue #175
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
cleveragents/cleveractors-core#180
No description provided.