fix(agents): reject malformed file_write path arguments before touching the filesystem #185
No reviewers
Labels
No labels
auto/blocked-by-deps
auto/ci-timeout
auto/claimed-implementer
auto/claimed-merge
auto/claimed-reviewer
auto/driver-down
auto/invariant-violation
auto/last-attempt-tier-0
auto/last-attempt-tier-1
auto/last-attempt-tier-2
auto/last-attempt-tier-min
Automation Tracking
auto/needs-conflict-resolution
auto/needs-implementer
auto/postmortem
auto/ready-to-merge
auto/restart-throttled
auto/revert
auto/sentinel
auto/stale-inactivity
auto/unstable
Blocked
Bounty
$100
Bounty
$1000
Bounty
$10000
Bounty
$20
Bounty
$2000
Bounty
$250
Bounty
$50
Bounty
$500
Bounty
$5000
Bounty
$750
MoSCoW
Could have
MoSCoW
Must have
MoSCoW
Should have
Needs Feedback
Points
1
Points
13
Points
2
Points
21
Points
3
Points
34
Points
5
Points
55
Points
8
Points
88
Priority
Backlog
Priority
CI Blocker
Priority
Critical
Priority
High
Priority
Low
Priority
Medium
Signed-off: Owner
Signed-off: Scrum Master
Signed-off: Tech Lead
Spike
State
Completed
State
Duplicate
State
In Progress
State
In Review
State
Paused
State
Unverified
State
Verified
State
Wont Do
Type
Automation
Type
Bug
Type
Discussion
Type
Documentation
Type
Epic
Type
Feature
Type
Legendary
Type
Refactor
Type
Support
Type
Task
Type
Testing
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Blocks
Reference
cleveragents/cleveractors-core!185
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "bugfix/m1-file-write-path-validation"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
ToolAgent._validate_file_path_safetyonly checked afile_writefileargument for traversal, absolute-path, and home-directory escapes. A corrupted path string (e.g. an LLM-hallucinated markup fragment concatenated onto a real path, or a whitespace-run from a bad string concatenation) passed validation unrejected and only failed deep insideFileAccessCore's OS call, surfacing an opaque[Errno 2]the agent had no way to self-correct from._validate_path_charactershelper: rejects ASCII control characters, markup/shell metacharacters (<,>,",|, backtick, backslash), and two-or-more consecutive whitespace characters, raising a descriptiveExecutionErrornaming the specific offending character(s)/pattern -- before any filesystem call._validate_file_path_safety(file_write) and_file_read_tool, per the issue's "apply consistently" subtask.@tdd_expected_failfrom the two@tdd_issue_175scenarios now that the bug is fixed (the underlying assertion now passes normally, not via inversion), and adds a control-character scenario, a legitimate-path regression scenario, and afile_readscenario for the consistency requirement.Per the mandatory Bug Fix TDD Workflow, the companion TDD issue #176 (tagged
@tdd_issue @tdd_issue_175 @tdd_expected_fail) was already written and merged first; this PR removes the@tdd_expected_failtag now that the fix lands.Test plan
nox -s unit_tests-- 3354 scenarios passing, including the 4 new/edited#175scenariosnox -s lint/nox -s format -- --check-- cleannox -s typecheck-- 0 errorsnox -s security_scan-- 0 findingsnox -s dead_code-- cleannox -s coverage_report-- 97.3% (threshold 96.5%)Closes #175
PR Review: !185 (Ticket #175)
Verdict: Approve
The fix faithfully implements ticket #175: a shared
_validate_path_charactershelper rejects control characters, markup/shell metacharacters, and 2+ whitespace runs before any filesystem call, applied consistently to bothfile_write(via_validate_file_path_safety) andfile_read, with traversal/absolute/home checks untouched. The TDD workflow is correctly completed (@tdd_expected_failremoved from the two@tdd_issue_175scenarios;@tdd_issue/@tdd_issue_175retained; #175 correctly blocked by the merged TDD issue #176). All acceptance criteria are met and the error message names the specific offending character/pattern (verified by direct execution). All quality gates were re-run locally on this branch:unit_tests3354 scenarios passed,lint/format --check/typecheck(0 errors)/security_scan/dead_codeclean,coverage_report97.3%, and the most-affected Robot suites (symlink_safe_open,llm_tool_calling) 18/18 passed. New code regions have no uncovered lines.Critical Issues
None
Major Issues
None
Minor Issues
Non-string
fileargument now surfaces as a rawTypeErrorinstead of a descriptiveExecutionError—src/cleveractors/agents/tool.py:84(_validate_path_characters), reached fromtool.py:1137andtool.py:1022. For a malformed type argument (e.g.{"file": 123}), iterating a non-strraisesTypeError: 'int' object is not iterable, which nothing catches. Verified empirically against this branch and the pre-fix commit: pre-fix the call raisedExecutionError: Invalid file path: _path_normpath: path should be string, bytes or os.PathLike, not int; post-fix, viaToolAgent.invoke()(Path B graph dispatch, which does not wrap exceptions) it is a rawTypeError, and viaprocess_messageit becomes the less actionableTool execution failed: 'int' object is not iterable. This works against the ticket's core goal ("a clearExecutionErrordescribing exactly what about the path is invalid … specific enough that the calling agent can self-correct"). Recommendation: add anisinstance(filepath, str)guard at the top of_validate_path_charactersraising a descriptiveExecutionError— this also fixes the same latent gap in_file_read_tool(whose shell-indicator check already crashed raw on non-strbefore this PR). Low severity: edge case, no security impact, not the ticket's reported scenario.Descriptive-message content is not asserted in the two updated
file_writerejection scenarios —features/tool_agent.feature:517-547, step atfeatures/steps/tool_agent_steps.py:272-295. The step only asserts anExecutionErroroccurred with no OS-error text; it would still pass if the message regressed to a generic one. The ticket's acceptance criterion ("names the specific invalid character(s)/pattern") is only asserted in the newfile_readscenario ("disallowed characters"); the whitespace-run message fragment ("consecutive whitespace") is asserted nowhere. Recommendation: strengthen the step (or the scenarios) to also assert the descriptive message fragments, locking in the self-correctability criterion.Nits
docs/tools/built-in-tools.mddocumentsfile_read's shell-command rejection heuristic (≈lines 211–214) but the new malformed-path rejection is not mentioned forfile_read/file_write. Not required by the ticket (CHANGELOG covers it) — optional docs follow-up.Summary
Clean, well-scoped bug fix that matches the ticket's subtasks point-for-point: helper created and called from
_validate_file_path_safety, consistency subtask satisfied (file_readis the only sibling tool taking a path argument — verified), Behave scenarios cover markup corruption, control characters, whitespace runs, and legitimate-path regression, and the mandatory TDD workflow is properly closed out. Coverage of the new code is complete and the repo-wide gates all pass locally. The two minor items above (non-strargument error quality; message-content assertions) are worth a small follow-up but do not block merge. Red-tape items (base branch, labels, commit footer) excluded per review instructions; the PR has no prior reviewer comments and no author decisions deferring any scope.4f67101a130228d7fa45@hurui200320 Thanks for the thorough review. I checked each point against the ticket's acceptance criteria (#175) and
docs/index.md§4.5 (which documentsfile_read/file_write'sfileargument as astring) before touching anything. Summary below; new head commit is0228d7f.Minor Issue 1 (non-string
fileargument) — Fixed, with a correction to the suggested fix locationConfirmed:
{"file": 123}onfile_writereached_validate_path_charactersuntyped and raised a rawTypeError: 'int' object is not iterableon the character-set comprehension. Fixed by adding anisinstance(filepath, str)guard at the top of_validate_path_characters, raisingExecutionError("File path must be a string, got {type}: {value!r}").However, I verified empirically that this fix alone does not also cover
_file_read_toolas suggested —_file_read_toolcrashes one step earlier, at its own shell-indicator heuristic (filepath.strip().split()[0]...), withAttributeError: 'int' object has no attribute 'strip', before_validate_path_charactersis ever called. Reproduced directly:So I moved the
_validate_path_characters(filepath)call in_file_read_toolto run immediately after the empty-path check, before the shell-indicator block, instead of after it. I checked this reordering doesn't change behavior for any existing scenario: the only characters shared between the shell-indicator set and the illegal-path-character set are<,>,|, and no current scenario/test exercises afile_readcall containing those alongside a shell-command-like string, so no precedence conflict was introduced. Added two new Behave scenarios (file_writeandfile_read, non-stringfileargument) to lock this in — both pass.Minor Issue 2 (message-content assertions) — Fixed
The shared step
the file write should be rejected by path validation before any filesystem callonly assertedExecutionError+ absence of"Errno"/"No such file", so a regression to a generic message would still pass. AddedAnd tool execution should fail with message containing "..."to all three affected scenarios (markup →"disallowed characters", whitespace-run →"consecutive whitespace", control-char →"disallowed characters"), reusing the existing generic step rather than writing a new one.Nit (docs/tools/built-in-tools.md) — Not done, per your own note
You flagged this as "Not required by the ticket... optional docs follow-up," so I left it out of this PR to keep the diff scoped to #175's acceptance criteria. Happy to pick it up separately if you'd rather it not wait.
"Small follow-up" framing — addressed directly in this PR, not as an independent follow-up
Both minor issues are fixed in this same commit (amended, not a new one — the branch isn't merged yet, so there's no "already-shipped" history to preserve) rather than spun out into a separate issue/PR, since they're small, directly tied to #175's scope, and the ticket is still open.
Verification
nox -s unit_tests: 3356/3356 scenarios pass (3354 → +2 new: non-stringfilefor both tools).features/tool_agent.feature(not the full-suite threshold run): every added/changed line intool.py(theisinstanceguard, its branch, and the reordered call site) is exercised — no new uncovered lines.nox -s lint/format -- --check/typecheck/security_scan/dead_code: all clean (one file neededruff format, now applied).Pushed to
bugfix/m1-file-write-path-validation(force-pushed, since the commit was amended — branch is unprotected). Re-requesting your review when convenient.0228d7fa45fe9ce14c59One more fix on top of the above, found during an informal discussion with the project owner rather than in your review, but worth recording here since it's in the same commit (
fe9ce14):Cross-platform (Windows) path separator — fixed
_ILLEGAL_PATH_CHARSincludes` \`because it's never legitimate content in a path segment (shell escape character). But the original whole-string character scan would also flag a native Windows path using\as its separator (e.g.subdir\leaf.v) as corrupted — this project has a confirmed requirement to run on Windows hosts (already evidenced by the bundled-skill-script support invoking.batfiles viacmd.exe, perdocs/guides/skill-packages.md/docs/tools/built-in-tools.md), so that's a real regression for that platform, not a theoretical one.Fix:
_validate_path_charactersnow splits the path into segments viapathlib.PurePathbefore scanning for illegal characters.PurePathresolves toPureWindowsPathorPurePosixPathbased onos.name— the same auto-detectionos.pathitself already relies on — so a Windows host's native\separator is consumed as a segment boundary and never seen by the character check, while on a POSIX host\is still not a separator and a string using it as one is still rejected (preserving the original hardening there). The leading anchor of an absolute/drive/UNC path is excluded from the character scan — its legality is handled separately by the existing absolute-path/traversal/sandbox checks downstream.Since CI only runs on Linux, added Behave scenarios that simulate
os.name == "nt"viaunittest.mock.patch(a standard, non-LLM test technique) to exercise the Windows branch deterministically: a Windows-style path is accepted end-to-end through_file_write_tool, an illegal character embedded in a Windows path segment is still rejected, and a bare backslash path is still rejected on the current (POSIX) CI host. All infeatures/tool_coverage_gaps.feature.Re-verified:
nox -s unit_tests3360/3360 scenarios pass; coverage delta scoped to the two pertinent feature files shows no new uncovered lines;lint/format/typecheck/security_scan/dead_codeall clean. Pushed asfe9ce14(force-pushed, amended, unprotected branch).