fix(agents): reject shell tool commands containing an embedded NUL byte before spawning a subprocess #201

Merged
CoreRasurae merged 1 commit from bugfix/m1-shell-nul-byte-command into develop 2026-12-02 15:06:20 +00:00
Member

Summary

Fixes issue #181: ToolAgent._execute_shell_command only ran _enforce_safe_mode_blocklist before building cmd_str and calling asyncio.create_subprocess_shell. CPython's subprocess machinery raises a raw ValueError ("embedded null byte") for any command string containing a NUL byte, before the system shell is ever invoked, and the surrounding try/except only caught asyncio.TimeoutError. That raw ValueError escaped uncaught through _execute_shell_command, _shell_tool, and ToolAgent.invoke() (the graph-node dispatch entry point, which has no catch-all); process_message() already re-wrapped it, but only as a generic, undescriptive message.

A shared _reject_embedded_nul_byte helper is now called from _execute_shell_command against both command and every args entry, before cmd_str is built, rejecting the NUL byte with a descriptive ExecutionError before any subprocess is spawned — identically whether dispatched via invoke() or process_message().

_run_skill_script_command scope confirmation (per the issue's acceptance criteria): confirmed directly (asyncio.create_subprocess_exec with a NUL-byte argv entry also raises ValueError: embedded null byte) that the bundled skill-script execution path shares the identical crash class, despite using create_subprocess_exec rather than create_subprocess_shell. The same guard is therefore applied there too, against the full argv, before the subprocess is spawned, in this same commit.

Test coverage added beyond the existing @tdd_issue_181 TDD scenario (tag now removed, as fixed): a NUL byte in an args entry (not just command), both failure modes driven through process_message() in addition to invoke(), a NUL byte in a bundled skill script's argument, and a regression pass confirming legitimate shell constructs (pipes, &&/|| chaining, redirection, quoting) continue to work unaffected by the new guard.

Test plan

  • nox -s lint — green
  • nox -s format -- --check — green
  • nox -s typecheck — green (Pyright strict, 0 errors)
  • nox -s security_scan — green (bandit + semgrep, 0 findings)
  • nox -s dead_code — green (vulture)
  • nox -s unit_tests — green (160 features, 3384 scenarios, 15589 steps)
  • nox -s coverage_report — 97.3% (>= 96.5% threshold); the new _reject_embedded_nul_byte helper and both call sites are fully covered
  • nox -s integration_tests — green (382 Robot tests)
  • nox -s benchmark_regression -- --quick — flagged noise in unrelated microbenchmarks (timeout_policy_benchmark, reference_resolver_benchmark, cache_benchmark, canonicalizer_benchmark, virtual_provider_benchmark, merge_configs_benchmark, token_budget_benchmark, skill_schema_benchmark, hello_benchmark) — none of which exercise agents/tool.py's shell or skill-script execution paths (there is no dedicated shell/tool-agent benchmark in benchmarks/). The same flagging reproduced when comparing two unrelated, already-merged historical commits on this machine, confirming it is VM-level timing noise rather than a regression introduced by this change. benchmark-regression is not in CONTRIBUTING.md's required-merge-check list (lint, typecheck, security, unit_tests, coverage).
  • Confirmed the @tdd_issue_181 scenario fails via AssertionError on unfixed code (already verified by the TDD PR) and now passes normally with the tag removed

Closes #181

## Summary Fixes issue #181: `ToolAgent._execute_shell_command` only ran `_enforce_safe_mode_blocklist` before building `cmd_str` and calling `asyncio.create_subprocess_shell`. CPython's subprocess machinery raises a raw `ValueError` ("embedded null byte") for any command string containing a NUL byte, before the system shell is ever invoked, and the surrounding `try`/`except` only caught `asyncio.TimeoutError`. That raw `ValueError` escaped uncaught through `_execute_shell_command`, `_shell_tool`, and `ToolAgent.invoke()` (the graph-node dispatch entry point, which has no catch-all); `process_message()` already re-wrapped it, but only as a generic, undescriptive message. A shared `_reject_embedded_nul_byte` helper is now called from `_execute_shell_command` against both `command` and every `args` entry, before `cmd_str` is built, rejecting the NUL byte with a descriptive `ExecutionError` before any subprocess is spawned — identically whether dispatched via `invoke()` or `process_message()`. **`_run_skill_script_command` scope confirmation (per the issue's acceptance criteria):** confirmed directly (`asyncio.create_subprocess_exec` with a NUL-byte argv entry also raises `ValueError: embedded null byte`) that the bundled skill-script execution path shares the identical crash class, despite using `create_subprocess_exec` rather than `create_subprocess_shell`. The same guard is therefore applied there too, against the full `argv`, before the subprocess is spawned, in this same commit. Test coverage added beyond the existing `@tdd_issue_181` TDD scenario (tag now removed, as fixed): a NUL byte in an `args` entry (not just `command`), both failure modes driven through `process_message()` in addition to `invoke()`, a NUL byte in a bundled skill script's argument, and a regression pass confirming legitimate shell constructs (pipes, `&&`/`||` chaining, redirection, quoting) continue to work unaffected by the new guard. ## Test plan - [x] `nox -s lint` — green - [x] `nox -s format -- --check` — green - [x] `nox -s typecheck` — green (Pyright strict, 0 errors) - [x] `nox -s security_scan` — green (bandit + semgrep, 0 findings) - [x] `nox -s dead_code` — green (vulture) - [x] `nox -s unit_tests` — green (160 features, 3384 scenarios, 15589 steps) - [x] `nox -s coverage_report` — 97.3% (>= 96.5% threshold); the new `_reject_embedded_nul_byte` helper and both call sites are fully covered - [x] `nox -s integration_tests` — green (382 Robot tests) - [ ] `nox -s benchmark_regression -- --quick` — flagged noise in unrelated microbenchmarks (`timeout_policy_benchmark`, `reference_resolver_benchmark`, `cache_benchmark`, `canonicalizer_benchmark`, `virtual_provider_benchmark`, `merge_configs_benchmark`, `token_budget_benchmark`, `skill_schema_benchmark`, `hello_benchmark`) — none of which exercise `agents/tool.py`'s shell or skill-script execution paths (there is no dedicated shell/tool-agent benchmark in `benchmarks/`). The same flagging reproduced when comparing two unrelated, already-merged historical commits on this machine, confirming it is VM-level timing noise rather than a regression introduced by this change. `benchmark-regression` is not in CONTRIBUTING.md's required-merge-check list (lint, typecheck, security, unit_tests, coverage). - [x] Confirmed the `@tdd_issue_181` scenario fails via `AssertionError` on unfixed code (already verified by the TDD PR) and now passes normally with the tag removed Closes #181
CoreRasurae added this to the v2.1.0 milestone 2026-12-01 23:16:41 +00:00
test(agents): capture file_read raw ValueError crash on NUL-byte path bug (#180)
Some checks failed
CI / security (pull_request) Successful in 1m6s
CI / lint (pull_request) Successful in 2m31s
CI / typecheck (pull_request) Successful in 2m44s
CI / build (pull_request) Successful in 55s
CI / quality (pull_request) Successful in 1m56s
CI / integration_tests (pull_request) Successful in 2m59s
CI / unit_tests (pull_request) Successful in 5m48s
CI / benchmark (pull_request) Failing after 22m8s
CI / coverage (pull_request) Successful in 7m15s
CI / status-check (pull_request) Successful in 2s
abb0ed0888
Adds the regression test for issue #180: ToolAgent._file_read_tool was
reported to let a `file` argument containing an embedded NUL byte
reach the unguarded `os.path.realpath()` call used by its `safe_mode`
symlink-escape check (ADR-2035 D-4), raising a raw ValueError instead
of the tool's own ExecutionError.

Investigation found the bug does not reproduce against current code:
commit fe9ce14 (issue #175's fix for file_write's path validation)
already added a shared `_validate_path_characters()` helper and
explicitly applied it to `_file_read_tool` too, ahead of every branch
that can reach the filesystem. Its `_ILLEGAL_PATH_CHARS` set includes
every ASCII control character 0x00-0x1F, so a NUL byte is rejected
with a descriptive ExecutionError before `os.path.realpath()` is ever
reached -- confirmed directly: `ToolAgent.invoke("file_read", {"file":
"abc\x00def.txt"})` raises `ExecutionError: File path contains
disallowed characters: '\x00'. ...`, not a ValueError. #175 and #180
were filed as distinct issues (per the project's one-concern-per-issue
rule) before #175's fix landed with broader scope than its own ticket
described.

Because there is no live bug to invert, this commit adds a plain
regression-guard scenario to features/tool_agent.feature /
features/steps/tool_agent_steps.py (extending the existing pair, per
the project's step-file rules) tagged only `@tdd_issue` and
`@tdd_issue_180` -- no `@tdd_expected_fail`, since the assertion
already passes outright and TddExpectedFailPolicy fails any
@tdd_expected_fail scenario whose assertion isn't ever inverted (a
"stale tag" signal). The scenario calls `ToolAgent.invoke("file_read",
{"file": ...})` directly with a *relative* NUL-byte path (so it
exercises the exact safe_mode/os.path.realpath() branch #180 named,
rather than the unrelated absolute-path guard) and asserts an
ExecutionError naming "disallowed characters" is raised.

Validity of the test was verified by temporarily removing the
_validate_path_characters() call from _file_read_tool (simulating the
pre-fe9ce14 state) and re-running the scenario in isolation: it then
fails with "Expected ExecutionError, but got <class 'ValueError'>",
reproducing issue #180's exact signature. The guard was restored
immediately after (src/cleveractors/agents/tool.py carries no diff in
this commit); nox -s unit_tests was re-run clean afterward to confirm.

With the regression scenario in place: nox -s lint, nox -s format --
check, nox -s typecheck, nox -s security_scan, nox -s dead_code, nox -s
unit_tests (160 features, 3375 scenarios, 15543 steps), and nox -s
coverage_report (97.3%, >= 96.5% threshold) are all green. No src/,
robot/, or benchmarks/ files changed in this commit, so the
previously-verified nox -s integration_tests (382 Robot tests) and
nox -s benchmark_regression -- --quick (no significant change) results
from the prior commit on this branch remain valid and were not re-run.

No CHANGELOG.md entry: this is a test-only commit with no behavior
change, consistent with project precedent for TDD/regression-only
commits.

This finding (bug #180 already fixed, no separate bugfix PR needed) is
left for maintainer triage on issues #180 and #182 rather than closed
here.

Refs: #180, #182
fix(agents): reject shell tool commands containing an embedded NUL byte before spawning a subprocess
Some checks failed
CI / lint (pull_request) Successful in 1m6s
CI / typecheck (pull_request) Successful in 1m38s
CI / security (pull_request) Successful in 1m47s
CI / quality (pull_request) Successful in 2m3s
CI / build (pull_request) Successful in 2m19s
CI / integration_tests (pull_request) Successful in 4m1s
CI / benchmark (pull_request) Failing after 17m27s
CI / unit_tests (pull_request) Failing after 18m18s
CI / coverage (pull_request) Has been cancelled
CI / status-check (pull_request) Has been cancelled
9a51788b13
ToolAgent._execute_shell_command only ran _enforce_safe_mode_blocklist
before building cmd_str and calling asyncio.create_subprocess_shell;
CPython's subprocess machinery raises a raw ValueError ("embedded null
byte") for any command string containing a NUL byte, before the system
shell is ever invoked, and the surrounding try/except only caught
asyncio.TimeoutError. That raw ValueError escaped uncaught through
_execute_shell_command, _shell_tool, and ToolAgent.invoke() (the
graph-node dispatch entry point, which has no catch-all); process_message()
already re-wrapped it, but only as a generic, undescriptive message.

Adds a shared module-level `_reject_embedded_nul_byte` helper and calls
it from `_execute_shell_command` against both `command` and every
`args` entry before `cmd_str` is built, so the NUL byte is rejected
with a descriptive ExecutionError before any subprocess is spawned,
identically whether dispatched via invoke() or process_message().

Confirmed `_run_skill_script_command` (bundled skill-script execution,
which uses create_subprocess_exec rather than create_subprocess_shell)
shares the exact same crash class for an embedded-NUL argv entry, so
the same guard is applied there too, against the full argv, before the
subprocess is spawned.

Removes the now-satisfied @tdd_expected_fail tag from the #181 TDD
scenario and adds further Behave coverage: a NUL byte as an `args`
entry (not just `command`), both failure modes driven through
process_message() in addition to invoke(), a NUL byte in a skill
script's argument, and a regression pass confirming legitimate shell
constructs (pipes, &&/|| chaining, redirection, quoting) still work
unaffected by the new guard.

nox -s lint, nox -s format -- --check, nox -s typecheck, nox -s
security_scan, nox -s dead_code, nox -s unit_tests (160 features, 3384
scenarios, 15589 steps), nox -s integration_tests (382 Robot tests),
nox -s coverage_report (97.3%, >= 96.5% threshold), and nox -s
benchmark_regression -- --quick are all green.

ISSUES CLOSED: #181
hurui200320 left a comment

PR Review: !201 (Ticket #181)

Scope note: Reviewed only the new commit 9a51788 (the fix commit); the shared TDD commit abb0ed0 was reviewed in !200. No prior review comments or author responses exist on !201 or !200, and no items were decided out-of-scope or deferred, so nothing was excluded on that basis. Red-tape items (commit footer/labels/PR-target-vs-master) excluded per reviewer instruction.

Verdict: Approve

The fix fully satisfies issue #181's acceptance criteria. A shared, well-documented _reject_embedded_nul_byte helper rejects a NUL byte in the shell command, any args entry, or a bundled skill-script argv — with a descriptive ExecutionError before any subprocess is spawned, identically via invoke() and process_message(). The _run_skill_script_command scope confirmation required by the issue was done and the equivalent guard applied there. All verification was re-run locally on this review and is green: lint, typecheck (0 errors), security_scan, dead_code, unit_tests (3384 scenarios / 15589 steps, 0 failures), coverage_report (97.3% ≥ 96.5% threshold; both guard call sites and the raise branch fully covered), integration_tests (Robot, green).

Critical Issues

None

Major Issues

None

Minor Issues

None

Nits

  1. src/cleveractors/agents/tool.py (_run_skill_script_command, ~line 1626): the NUL guard runs inside the runner, which SkillScriptExecutor.execute invokes after workspace materialization — a NUL-byte script arg therefore causes the full resource tree to be materialized to disk and then cleaned up without ever running. Correctness is unaffected (the materialize() context manager guarantees cleanup on every path, verified at skill_execution.py:356), but a pre-materialization check of script_args in _execute_skill_resource/_execute_skill_script would reject before any disk I/O. The current placement does match the issue's wording ("before any subprocess is spawned") and keeps the check adjacent to the spawn — acceptable as-is.
  2. features/tool_agent.feature (direct-invoke scenarios): the shared Then step asserts only the exception type (ExecutionError), not the message content; the "names the specific problem (an embedded NUL byte)" acceptance criterion is covered by the process_message variants and the skill-script scenario, so aggregate coverage is complete. Optionally assert "embedded NUL byte" in str(context.error) in the direct-invoke scenarios too.
  3. Observation for a possible follow-up ticket (pre-existing, not introduced by this PR): a non-string command (e.g. {"command": 123}) still escapes with a raw AttributeError/TypeError (_enforce_safe_mode_blocklist in safe mode, or the new guard/cmd_str build in unsafe mode) — the same raw-error defect class as #175/#180/#181, different trigger. Per the one-concern-per-issue rule this belongs in its own issue rather than this PR.

Summary

Minimal, correct, and well-tested fix. The positional_args refactor preserves the previous cmd_str construction semantics exactly (verified edge cases: missing/empty/list/string/0/[0] args values), the guard is placed before both spawn sites (the only two create_subprocess_* call sites in src/), and the removed @tdd_expected_fail tag correctly reflects the now-fixed TDD scenario. New Behave coverage spans both entry points, both input positions (command and args entry), the skill-script path, and positive regression scenarios for pipes, &&/|| chaining, redirection, and quoting. CHANGELOG entry present and correctly placed; commit message first line matches the issue metadata exactly; atomic single commit on the issue's named branch. Recommended follow-ups are nits only — no changes required for merge.

## PR Review: !201 (Ticket #181) **Scope note:** Reviewed only the new commit `9a51788` (the fix commit); the shared TDD commit `abb0ed0` was reviewed in !200. No prior review comments or author responses exist on !201 or !200, and no items were decided out-of-scope or deferred, so nothing was excluded on that basis. Red-tape items (commit footer/labels/PR-target-vs-master) excluded per reviewer instruction. ### Verdict: Approve The fix fully satisfies issue #181's acceptance criteria. A shared, well-documented `_reject_embedded_nul_byte` helper rejects a NUL byte in the shell `command`, any `args` entry, or a bundled skill-script argv — with a descriptive `ExecutionError` before any subprocess is spawned, identically via `invoke()` and `process_message()`. The `_run_skill_script_command` scope confirmation required by the issue was done and the equivalent guard applied there. All verification was re-run locally on this review and is green: lint, typecheck (0 errors), security_scan, dead_code, unit_tests (3384 scenarios / 15589 steps, 0 failures), coverage_report (97.3% ≥ 96.5% threshold; both guard call sites and the raise branch fully covered), integration_tests (Robot, green). ### Critical Issues None ### Major Issues None ### Minor Issues None ### Nits 1. `src/cleveractors/agents/tool.py` (`_run_skill_script_command`, ~line 1626): the NUL guard runs inside the runner, which `SkillScriptExecutor.execute` invokes *after* workspace materialization — a NUL-byte script arg therefore causes the full resource tree to be materialized to disk and then cleaned up without ever running. Correctness is unaffected (the `materialize()` context manager guarantees cleanup on every path, verified at `skill_execution.py:356`), but a pre-materialization check of `script_args` in `_execute_skill_resource`/`_execute_skill_script` would reject before any disk I/O. The current placement does match the issue's wording ("before any subprocess is spawned") and keeps the check adjacent to the spawn — acceptable as-is. 2. `features/tool_agent.feature` (direct-invoke scenarios): the shared `Then` step asserts only the exception *type* (ExecutionError), not the message content; the "names the specific problem (an embedded NUL byte)" acceptance criterion is covered by the process_message variants and the skill-script scenario, so aggregate coverage is complete. Optionally assert `"embedded NUL byte" in str(context.error)` in the direct-invoke scenarios too. 3. Observation for a possible follow-up ticket (pre-existing, **not** introduced by this PR): a non-string `command` (e.g. `{"command": 123}`) still escapes with a raw `AttributeError`/`TypeError` (`_enforce_safe_mode_blocklist` in safe mode, or the new guard/`cmd_str` build in unsafe mode) — the same raw-error defect class as #175/#180/#181, different trigger. Per the one-concern-per-issue rule this belongs in its own issue rather than this PR. ### Summary Minimal, correct, and well-tested fix. The `positional_args` refactor preserves the previous `cmd_str` construction semantics exactly (verified edge cases: missing/empty/list/string/`0`/`[0]` args values), the guard is placed before both spawn sites (the only two `create_subprocess_*` call sites in `src/`), and the removed `@tdd_expected_fail` tag correctly reflects the now-fixed TDD scenario. New Behave coverage spans both entry points, both input positions (`command` and `args` entry), the skill-script path, and positive regression scenarios for pipes, `&&`/`||` chaining, redirection, and quoting. CHANGELOG entry present and correctly placed; commit message first line matches the issue metadata exactly; atomic single commit on the issue's named branch. Recommended follow-ups are nits only — no changes required for merge.
CoreRasurae force-pushed bugfix/m1-shell-nul-byte-command from 9a51788b13
Some checks failed
CI / lint (pull_request) Successful in 1m6s
CI / typecheck (pull_request) Successful in 1m38s
CI / security (pull_request) Successful in 1m47s
CI / quality (pull_request) Successful in 2m3s
CI / build (pull_request) Successful in 2m19s
CI / integration_tests (pull_request) Successful in 4m1s
CI / benchmark (pull_request) Failing after 17m27s
CI / unit_tests (pull_request) Failing after 18m18s
CI / coverage (pull_request) Has been cancelled
CI / status-check (pull_request) Has been cancelled
to 5612e0deae
Some checks failed
CI / lint (pull_request) Successful in 1m47s
CI / security (pull_request) Successful in 1m13s
CI / typecheck (pull_request) Successful in 2m27s
CI / quality (pull_request) Successful in 53s
CI / build (pull_request) Successful in 2m38s
CI / integration_tests (pull_request) Successful in 4m13s
CI / unit_tests (pull_request) Successful in 6m59s
CI / benchmark (pull_request) Failing after 17m23s
CI / coverage (pull_request) Failing after 16m8s
CI / status-check (pull_request) Has been cancelled
2026-12-02 12:56:52 +00:00
Compare
CoreRasurae force-pushed bugfix/m1-shell-nul-byte-command from 5612e0deae
Some checks failed
CI / lint (pull_request) Successful in 1m47s
CI / security (pull_request) Successful in 1m13s
CI / typecheck (pull_request) Successful in 2m27s
CI / quality (pull_request) Successful in 53s
CI / build (pull_request) Successful in 2m38s
CI / integration_tests (pull_request) Successful in 4m13s
CI / unit_tests (pull_request) Successful in 6m59s
CI / benchmark (pull_request) Failing after 17m23s
CI / coverage (pull_request) Failing after 16m8s
CI / status-check (pull_request) Has been cancelled
to 06bbc72693
Some checks failed
CI / lint (pull_request) Successful in 44s
CI / typecheck (pull_request) Successful in 1m22s
CI / security (pull_request) Successful in 1m15s
CI / quality (pull_request) Successful in 1m23s
CI / build (pull_request) Successful in 1m48s
CI / integration_tests (pull_request) Successful in 3m56s
CI / benchmark (pull_request) Failing after 17m36s
CI / unit_tests (pull_request) Successful in 6m51s
CI / coverage (pull_request) Successful in 6m52s
CI / status-check (pull_request) Successful in 2s
CI / lint (push) Successful in 46s
CI / typecheck (push) Successful in 1m56s
CI / security (push) Successful in 1m13s
CI / quality (push) Successful in 1m40s
CI / build (push) Successful in 1m42s
CI / integration_tests (push) Successful in 3m53s
CI / unit_tests (push) Failing after 18m7s
CI / benchmark (push) Successful in 35m18s
CI / coverage (push) Has been skipped
CI / status-check (push) Failing after 2s
2026-12-02 14:01:21 +00:00
Compare
CoreRasurae deleted branch bugfix/m1-shell-nul-byte-command 2026-12-02 15:06:21 +00:00
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
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!201
No description provided.