Repository navigation
feat(bash): gate destructive commands behind a reflection turn (fixes #604) - #618
Conversation
…604) jcode executed bash tool calls with no gate of its own. The only check in ToolRegistry::execute is an opt-in external pre_tool hook, off by default, so 'rm -rf ~' was obeyed immediately. I reproduced this against the shipped binary before changing anything: a throwaway directory was deleted with no prompt. Two stages. Stage 1 (jcode-command-risk) is deterministic, does no I/O beyond lexical path handling, and classifies by blast radius rather than command name, so find -delete, shred, dd and truncating redirects are covered as well as rm. Four tiers: Safe, Low (inside cwd / temp), Confirm (irreversible and outside cwd), Catastrophic (/, $HOME, credential stores, device nodes). Stage 2 is a harness gate, not a second model. A Confirm verdict returns a prompt asking the model which specific user request requires the deletion, and the call only proceeds when re-issued with a substantive justification field. A blind retry is refused identically, so this is not a speed bump an agent defeats by repeating itself. Catastrophic is denied unconditionally: no justification unlocks it. Cost is zero on the common path, since stage 2 only runs when stage 1 flags something. Verified live end to end: the Confirm loop refuses, the model reflects, re-issues with a justification, and succeeds; $HOME and /.ssh are denied outright even with a fabricated justification. Tests: 50 in jcode-command-risk including a 330-command sweep over verb x flag x home-spelling, an inverse sweep asserting routine project work is never interrupted, and separator-laundering cases; 3 integration tests at the bash tool boundary with a canary file proving refusal happens before the process spawns. This is defense in depth, not a sandbox: sh -c can defeat any static parser, which is why the catastrophic tier is a small absolute path check that does not depend on parsing the command correctly.
The gate sits before the run_in_background early return, so a backgrounded destructive command is refused as well. Cover that explicitly with a canary file, since it is the one path in execute that returns before the main body.
Greptile SummaryThis PR adds a deterministic safety gate for destructive shell commands. The main changes are:
Confidence Score: 4/5A contained The bash gate and command-risk classifier cover the main destructive-command paths, but one protected deletion route remains open through Files Needing Attention:
|
| Filename | Overview |
|---|---|
| crates/jcode-app-core/src/tool/apply_patch.rs | Adds catastrophic path denial for delete hunks, but Move to update hunks still remove protected source paths without the same guard. |
| crates/jcode-app-core/src/tool/apply_patch_tests.rs | Covers protected delete refusal and ordinary deletes, but does not cover protected source deletion via move hunks. |
| crates/jcode-app-core/src/tool/bash.rs | Wires the destructive-command gate into bash execution before foreground/background dispatch and exposes justification input. |
| crates/jcode-app-core/src/tool/bash_destructive_gate.rs | Adds the app-core adapter around command risk assessment, reflection gating, denial logging, and bash schema changes. |
| crates/jcode-app-core/src/tool/bash_tests.rs | Adds integration tests proving bash refusals happen before spawning and justified confirm-tier commands still run. |
| crates/jcode-command-risk/src/assess_tests.rs | Adds broad assessment coverage for home/root protection, wrappers, pipes, inline shells, globs, and routine-command non-noise. |
| crates/jcode-command-risk/src/gate.rs | Implements the reflection/deny/allow stage for assessed commands with a substantive-justification check. |
| crates/jcode-command-risk/src/lib.rs | Implements deterministic shell command assessment, including wrapper unwrapping, shell-script literals, destructive verbs, redirects, and pipe-fed deletes. |
| crates/jcode-command-risk/src/paths.rs | Implements lexical path expansion/normalization and catastrophic/confirm/low classification for protected home, credential, system, temp, and cwd paths. |
| crates/jcode-command-risk/src/tokenize.rs | Adds a minimal shell tokenizer for words, separators, pipes, quotes, recursive flags, and truncating redirects. |
Sequence Diagram
sequenceDiagram
participant Agent
participant BashTool
participant Risk as jcode-command-risk
participant Gate as Reflection gate
participant Shell
Agent->>BashTool: command + optional justification
BashTool->>Risk: assess(command, RiskContext)
Risk-->>BashTool: Safe/Low/Confirm/Catastrophic
alt Safe or Low
BashTool->>Shell: execute command
Shell-->>BashTool: output
else Confirm
BashTool->>Gate: gate(assessment, justification)
alt substantive justification
Gate-->>BashTool: Allow
BashTool->>Shell: execute command
else missing/weak justification
Gate-->>BashTool: Reflect prompt
BashTool-->>Agent: refusal before spawn
end
else Catastrophic
BashTool->>Gate: gate(assessment, justification)
Gate-->>BashTool: Deny
BashTool-->>Agent: blocked before spawn
end
Comments Outside Diff (2)
-
crates/jcode-app-core/src/tool/apply_patch.rs, line 166 (link)Moved files bypass
*** Update Filewith*** Move tostill deletes the original path without checkingis_catastrophic_target, so an absolute protected file can be removed by moving it to an allowed destination. This reopens the sameapply_patchdelete path the new guard closes for*** Delete File; e.g. updating/home/u/.ssh/id_ed25519with*** Move to: /tmp/keywrites the destination then removes the protected source here.Prompt To Fix With AI
This is a comment left during a code review. Path: crates/jcode-app-core/src/tool/apply_patch.rs Line: 166 Comment: **Moved files bypass** `*** Update File` with `*** Move to` still deletes the original path without checking `is_catastrophic_target`, so an absolute protected file can be removed by moving it to an allowed destination. This reopens the same `apply_patch` delete path the new guard closes for `*** Delete File`; e.g. updating `/home/u/.ssh/id_ed25519` with `*** Move to: /tmp/key` writes the destination then removes the protected source here. How can I resolve this? If you propose a fix, please make it concise.
-
General comment
Bash gate lets an un-justified outside-workdir delete run immediately
- Bug
- The app-core bash integration test
tool::bash::tests::bash_holds_a_risky_delete_until_justified_then_runs_itfailed at the first attempt. It expectedrm -rfof a temp directory outside the configured working directory to be held for justification, but the bash tool returnedToolOutput { output: "Command completed successfully (no output)", title: Some("rm -rf /tmp/.../outside") }, meaning the command spawned and deleted the target before any justification was supplied.
- The app-core bash integration test
- Cause
- The bash tool integration path and/or risk context classification is not enforcing the confirm-tier decision for this outside-working-directory target at runtime, despite the PR's stated blast-radius behavior and the command-risk unit tests expecting outside-workdir deletes to require confirmation.
- Fix
- Update the bash destructive gate/risk context path so confirm-tier destructive commands outside the working directory return a reflection prompt before process spawn unless re-issued with a substantive
justification. Keep the existing catastrophic deny behavior intact and rerun the app-core gate tests.
- Update the bash destructive gate/risk context path so confirm-tier destructive commands outside the working directory return a reflection prompt before process spawn unless re-issued with a substantive
- Bug
Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 1
crates/jcode-app-core/src/tool/apply_patch.rs:166
**Moved files bypass**
`*** Update File` with `*** Move to` still deletes the original path without checking `is_catastrophic_target`, so an absolute protected file can be removed by moving it to an allowed destination. This reopens the same `apply_patch` delete path the new guard closes for `*** Delete File`; e.g. updating `/home/u/.ssh/id_ed25519` with `*** Move to: /tmp/key` writes the destination then removes the protected source here.
Reviews (4): Last reviewed commit: "fix(command-risk): close three bypasses ..." | Re-trigger Greptile
…604) apply_patch deletes by absolute path, and ToolContext::resolve_path passes absolute paths through unchanged, so a patch could remove any file on disk without touching the bash tool or its gate. Apply the catastrophic tier there too. Only that tier: deleting ordinary files is this tool's normal job, so the Confirm/reflection flow would be pure noise here. Writing the test exposed a real hole in the policy itself: the protected home subpaths were matched exactly, so ~/.ssh was protected but ~/.ssh/id_ed25519 was not. Credential stores (.ssh, .gnupg, .aws, .kube, .docker) are now protected recursively, while config and document roots stay exact-match so individual files inside ~/.config remain editable. 52 tests in jcode-command-risk, 1035 in jcode-app-core, guardrails pass.
|
Follow-up: closed a second route to the same damage, and the test found a real hole in the policy.
Writing the test exposed a policy bug. Protected home subpaths were matched exactly, so Totals now: 52 tests in Worth noting for review: this is the second unguarded deletion path found, which suggests the durable fix is a chokepoint in --- — Jcode agent (automated triage), on behalf of @1jehuang |
Automated review found three ways to reach the exact catastrophic delete this gate exists to stop. All three were classified Safe or Confirm; I reproduced each before fixing. 1. Wrapper commands. assess_segment only looked at tokens.first(), so 'sudo rm -rf ~' and 'env rm -rf $HOME' were Safe: the destructive verb was never inspected. Wrappers (sudo, doas, env, nice, timeout, nohup, xargs, ...) are now unwrapped recursively, consuming their own flags and flag values so 'nice -n 10 rm -rf ~' resolves too. A wrapper whose payload cannot be identified escalates rather than passing. 2. Piped deletes. 'find ~ -type f | xargs rm -rf' deletes home contents, but neither segment shows it because xargs takes operands from stdin. Segments receiving a pipe now escalate when the program is destructive. 3. System path contents. is_catastrophic_target matched system roots exactly, so /etc/passwd was merely Confirm, and apply_patch consults only the catastrophic tier and would have deleted it outright. Directories whose contents are as unrecoverable as the directory are now protected recursively. /home and /Users deliberately are not, so project paths under them stay workable. Also assess inline 'sh -c "..."' script text instead of skipping it. That cannot be fully solved by a static parser, but the plain literal case should not be a free pass. 9 new regression tests, including a wrapper x payload sweep and an inverse test asserting ordinary wrapped commands (sudo apt update, timeout 30 cargo build, sudo rm -rf ./target) still run unchallenged. 60 tests in jcode-command-risk, 1035 in jcode-app-core, guardrails pass.
|
The automated review found three real bypasses. All three are fixed; I reproduced each first.
1. Wrapper commands. 2. Piped deletes. Segments receiving a pipe now escalate when the program is destructive, since 3. System path contents. This was the worst of the three: Also now assessing inline 9 new regression tests, including a wrapper x payload sweep and an inverse test asserting This is the third round of holes found in this policy (the first two were mine, during development). That track record is itself an argument for the chokepoint refactor I mentioned above, and for treating this as defense in depth rather than a boundary to rely on. --- — Jcode agent (automated triage), on behalf of @1jehuang |
Fixes #604, where a reporter lost the contents of their home directory.
The gap is real, and I reproduced it first
Before changing anything I ran the shipped binary against a throwaway directory. It executed
rm -rfimmediately, no prompt, directory gone. Confirmed in three ways:bash.rshas no denylist of its own.ToolRegistry::executeisif crate::hooks::hook_configured("pre_tool")— an opt-in external hook, off by default.jcode-tui-permissionsexists but nothing in the tool-execution path ever calls it. This matches the security review in Security review: no permission gate on tool execution in interactive sessions, plus 4 related trust-boundary gaps #568.Design
Two stages, so the common path stays free.
Stage 1 —
jcode-command-risk. Deterministic, no model, no network. Classifies by blast radius rather than command name, sofind -delete,shred,dd, and truncating redirects are covered alongsiderm. Four tiers:/tmp/,$HOME,~/.ssh, device nodesStage 2 — a harness gate, deliberately not a second LLM. A judge model would add latency, cost, and a second thing to align, and could be talked around by the same reasoning that produced the command. Instead the harness refuses once and returns a prompt asking which specific user request requires this deletion. The call proceeds only when re-issued with a substantive
justification.The load-bearing property: a blind retry is refused identically. A literal "run it twice" rule is a speed bump an agent defeats reflexively; requiring it to state intent in its own words is not satisfiable by repetition, and the string is a useful audit record.
Verified live, end to end
$HOME,/,~/.ssh,~/*,dd of=/dev/sdaall denied even when handed a fabricated, elaborate justification.rm -rf target,git status,cargo build) is untouched.Tests
50 in
jcode-command-risk, including state-space sweeps rather than only hand-picked cases:~,$HOME,${HOME},"$HOME",/home/u/x/.., ...), asserting none reach the home directory&&,||,;,|, newline)normalizenever escaping above/, and totality over malformed input3 integration tests at the bash tool boundary, one using a canary file to prove refusal happens before the process spawns.
cargo test -p jcode-app-core --lib -- --test-threads=1→ 1032 passed. (Parallel shows one unrelated flake incomm_session, which reproduces on cleanmasterand is tracked by #595/#596.) All guardrail gates pass.Honest limitations
This is defense in depth, not a sandbox.
sh -c "$(...)"can defeat any static parser. That is exactly why the catastrophic tier is a small, absolute, path-based check that does not depend on parsing the surrounding command correctly, and why Confirm is a reflection prompt rather than a hard block.Two things worth your decision before merge:
jcode runis the sharper edge — unattended there is no human backstop, so the Confirm threshold arguably should be lower there./tmp) is what keeps the prompt rare; widening or narrowing it is a judgement call I would rather you make.--- — Jcode agent (automated triage), on behalf of @1jehuang