Compare commits

..
Author SHA1 Message Date
Patrick szymkowiak 76d6508f9e fix(hook): omit permissionDecision on allow to fix bypassPermissions mode (#893)
When Claude Code runs in bypassPermissions mode, it skips the
hookPermissionResult path entirely — discarding updatedInput that
accompanies a permissionDecision. This caused RTK rewrites to be
silently ignored.

Fix: for Allow verdict, omit permissionDecision from hook output.
Omitting = allow by default, AND updatedInput is processed correctly
in bypassPermissions mode. Ask verdict still includes
permissionDecision: "ask" explicitly.

Applied to both rtk-rewrite.sh (Claude Code) and hook_cmd.rs
(Copilot VS Code).

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-04-03 09:01:48 +02:00
Patrick szymkowiak d9ef47f998 docs(hooks): document permission precedence model in README
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-04-02 20:28:51 +02:00
Patrick szymkowiak 41a6c6bf6d fix(security): default to ask when no permission rule matches (#886)
Previously, commands not in any deny/ask list were auto-allowed. This
bypassed Claude Code's least-privilege default where unlisted commands
should prompt the user for confirmation.

Permission precedence is now: Deny > Ask > Allow (explicit) > Default (ask).

Changes:
- permissions.rs: load allow rules from settings.json, add Default variant
- rewrite_cmd.rs: treat Default same as Ask (exit 3)
- hook_cmd.rs: add permission checks to Copilot VS Code hook (ask/allow/deny),
  add deny check to Gemini hook (no ask mode available in Gemini CLI)

Gemini CLI limitation: only supports allow/deny, no ask mode. Codex: ask
is parsed but fails open. These tools document the limitation.

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-04-02 19:15:30 +02:00
6 changed files with 179 additions and 46 deletions

No files matched your search

+8 -4
View File
@@ -83,24 +83,28 @@ ORIGINAL_INPUT=$(echo "$INPUT" | jq -c '.tool_input')
UPDATED_INPUT=$(echo "$ORIGINAL_INPUT" | jq --arg cmd "$REWRITTEN" '.command = $cmd')
if [ "$EXIT_CODE" -eq 3 ]; then
# Ask: rewrite the command, omit permissionDecision so Claude Code prompts.
# Ask/Default: rewrite the command, include permissionDecision "ask"
# so Claude Code prompts the user for confirmation.
# In bypassPermissions mode this is ignored (command still rewrites correctly).
jq -n \
--argjson updated "$UPDATED_INPUT" \
'{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "ask",
"permissionDecisionReason": "RTK: no explicit allow rule",
"updatedInput": $updated
}
}'
else
# Allow: output the rewrite instruction in Claude Code hook format.
# Allow (explicit rule matched): rewrite without permissionDecision.
# Omitting permissionDecision = allow by default, AND works correctly
# in bypassPermissions mode (updatedInput is not discarded). Fixes #893.
jq -n \
--argjson updated "$UPDATED_INPUT" \
'{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"permissionDecisionReason": "RTK auto-rewrite",
"updatedInput": $updated
}
}'
+1 -3
View File
@@ -3,7 +3,6 @@
use crate::core::config;
use crate::core::tracking;
use crate::core::utils::{exit_code_from_output, exit_code_from_status, resolved_command};
use std::process::Stdio;
use anyhow::{Context, Result};
use std::ffi::OsString;
use std::process::Command;
@@ -909,7 +908,6 @@ fn run_commit(args: &[String], verbose: u8, global_args: &[String]) -> Result<i3
}
let output = build_commit_command(args, global_args)
.stdin(Stdio::inherit())
.output()
.context("Failed to run git commit")?;
@@ -974,7 +972,7 @@ fn run_push(args: &[String], verbose: u8, global_args: &[String]) -> Result<i32>
cmd.arg(arg);
}
let output = cmd.stdin(Stdio::inherit()).output().context("Failed to run git push")?;
let output = cmd.output().context("Failed to run git push")?;
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
+33
View File
@@ -61,6 +61,39 @@ Controls how `rtk init` modifies agent settings files:
All file operations use atomic writes (tempfile + rename) to prevent corruption on crash. Settings files are backed up to `.bak` before modification. All operations are idempotent -- running `rtk init` multiple times is safe.
## Permission Model
RTK enforces a permission precedence that matches Claude Code's least-privilege default:
```
Deny > Ask > Allow (explicit) > Default (ask)
```
Rules are loaded from all Claude Code `settings.json` files (project + global, including `.local` variants). Only `Bash(...)` rules are extracted; other scopes (Read, Write) are ignored.
| Verdict | Trigger | rewrite_cmd exit | Hook behavior |
|---------|---------|-----------------|---------------|
| Deny | `permissions.deny` rule matched | 2 | Passthrough — host tool handles denial |
| Ask | `permissions.ask` rule matched | 3 | Rewrite + let host tool prompt user |
| Allow | `permissions.allow` rule matched | 0 | Rewrite + auto-allow |
| Default | No rule matched | 3 | Rewrite + let host tool prompt user |
### Per-tool support
| Tool | ask support | Behavior on Default |
|------|------------|-------------------|
| Claude Code (rtk-rewrite.sh) | Yes | `permissionDecision: "ask"` — user prompted |
| Copilot VS Code (rtk hook copilot) | Yes | `permissionDecision: "ask"` — user prompted |
| Gemini CLI (rtk hook gemini) | No (allow/deny only) | allow (limitation — no ask mode in Gemini) |
| Copilot CLI (rtk hook copilot) | No updatedInput | deny-with-suggestion (unchanged) |
| Codex | ask parsed but no-op | allow (limitation — fails open) |
### Implementation
- `permissions.rs` — loads deny/ask/allow rules, evaluates precedence, returns `PermissionVerdict`
- `rewrite_cmd.rs` — maps verdict to exit code (consumed by shell hook)
- `hook_cmd.rs` — maps verdict to JSON `permissionDecision` field (Copilot/Gemini)
## Exit Code Contract
Hook processors in `hook_cmd.rs` must return `Ok(())` on every path — success, no-match, parse error, and unexpected input. Returning `Err` propagates to `main()` and exits non-zero, which blocks the agent's command from executing. This violates the non-blocking guarantee documented in `hooks/README.md`.
+33 -8
View File
@@ -6,6 +6,7 @@ use serde_json::{json, Value};
use std::io::{self, Read};
use crate::discover::registry::rewrite_command;
use crate::hooks::permissions::{check_command, PermissionVerdict};
// ── Copilot hook (VS Code + Copilot CLI) ──────────────────────
@@ -111,14 +112,32 @@ fn handle_vscode(cmd: &str) -> Result<()> {
None => return Ok(()),
};
let output = json!({
"hookSpecificOutput": {
"hookEventName": PRE_TOOL_USE_KEY,
"permissionDecision": "allow",
"permissionDecisionReason": "RTK auto-rewrite",
"updatedInput": { "command": rewritten }
}
});
let verdict = check_command(cmd);
// Deny: pass through without rewrite — let the host tool handle it.
if verdict == PermissionVerdict::Deny {
return Ok(());
}
// Allow (explicit rule matched): omit permissionDecision so updatedInput
// works in bypassPermissions mode (#893). Omitting = allow by default.
// Ask/Default: include permissionDecision "ask" to prompt the user.
let output = match verdict {
PermissionVerdict::Allow => json!({
"hookSpecificOutput": {
"hookEventName": PRE_TOOL_USE_KEY,
"updatedInput": { "command": rewritten }
}
}),
_ => json!({
"hookSpecificOutput": {
"hookEventName": PRE_TOOL_USE_KEY,
"permissionDecision": "ask",
"permissionDecisionReason": "RTK: no explicit allow rule",
"updatedInput": { "command": rewritten }
}
}),
};
println!("{output}");
Ok(())
}
@@ -170,6 +189,12 @@ pub fn run_gemini() -> Result<()> {
return Ok(());
}
// Check deny rules — Gemini CLI only supports allow/deny (no ask mode).
if check_command(cmd) == PermissionVerdict::Deny {
println!(r#"{{"decision":"deny","reason":"Blocked by RTK permission rule"}}"#);
return Ok(());
}
// Delegate to the single source of truth for command rewriting
match rewrite_command(cmd, &[]) {
Some(rewritten) => print_rewrite(&rewritten),
+103 -30
View File
@@ -5,22 +5,24 @@ use std::path::PathBuf;
/// Verdict from checking a command against Claude Code's permission rules.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum PermissionVerdict {
/// No deny/ask rules matched — safe to auto-allow.
/// An explicit allow rule matched — safe to auto-allow.
Allow,
/// A deny rule matched — pass through to Claude Code's native deny handling.
Deny,
/// An ask rule matched — rewrite the command but let Claude Code prompt the user.
Ask,
/// No rule matched — default to ask (matches Claude Code's least-privilege default).
Default,
}
/// Check `cmd` against Claude Code's deny/ask permission rules.
/// Check `cmd` against Claude Code's deny/ask/allow permission rules.
///
/// Returns `Allow` when no rules match (preserves existing behavior),
/// `Deny` when a deny rule matches, or `Ask` when an ask rule matches.
/// Deny takes priority over Ask if both match the same command.
/// Precedence: Deny > Ask > Allow > Default (ask).
/// Returns `Default` when no rules match — callers should treat this as ask
/// to match Claude Code's least-privilege default.
pub fn check_command(cmd: &str) -> PermissionVerdict {
let (deny_rules, ask_rules) = load_deny_ask_rules();
check_command_with_rules(cmd, &deny_rules, &ask_rules)
let (deny_rules, ask_rules, allow_rules) = load_permission_rules();
check_command_with_rules(cmd, &deny_rules, &ask_rules, &allow_rules)
}
/// Internal implementation allowing tests to inject rules without file I/O.
@@ -28,9 +30,11 @@ pub(crate) fn check_command_with_rules(
cmd: &str,
deny_rules: &[String],
ask_rules: &[String],
allow_rules: &[String],
) -> PermissionVerdict {
let segments = split_compound_command(cmd);
let mut any_ask = false;
let mut any_allow = false;
for segment in &segments {
let segment = segment.trim();
@@ -38,6 +42,7 @@ pub(crate) fn check_command_with_rules(
continue;
}
// Deny takes highest priority
for pattern in deny_rules {
if command_matches_pattern(segment, pattern) {
return PermissionVerdict::Deny;
@@ -52,16 +57,28 @@ pub(crate) fn check_command_with_rules(
}
}
}
if !any_allow && !any_ask {
for pattern in allow_rules {
if command_matches_pattern(segment, pattern) {
any_allow = true;
break;
}
}
}
}
// Precedence: Deny > Ask > Allow > Default (ask)
if any_ask {
PermissionVerdict::Ask
} else {
} else if any_allow {
PermissionVerdict::Allow
} else {
PermissionVerdict::Default
}
}
/// Load deny and ask Bash rules from all Claude Code settings files.
/// Load deny, ask, and allow Bash rules from all Claude Code settings files.
///
/// Files read (in order, later files do not override earlier ones — all are merged):
/// 1. `$PROJECT_ROOT/.claude/settings.json`
@@ -70,9 +87,10 @@ pub(crate) fn check_command_with_rules(
/// 4. `~/.claude/settings.local.json`
///
/// Missing files and malformed JSON are silently skipped.
fn load_deny_ask_rules() -> (Vec<String>, Vec<String>) {
fn load_permission_rules() -> (Vec<String>, Vec<String>, Vec<String>) {
let mut deny_rules = Vec::new();
let mut ask_rules = Vec::new();
let mut allow_rules = Vec::new();
for path in get_settings_paths() {
let Ok(content) = std::fs::read_to_string(&path) else {
@@ -87,9 +105,10 @@ fn load_deny_ask_rules() -> (Vec<String>, Vec<String>) {
append_bash_rules(permissions.get("deny"), &mut deny_rules);
append_bash_rules(permissions.get("ask"), &mut ask_rules);
append_bash_rules(permissions.get("allow"), &mut allow_rules);
}
(deny_rules, ask_rules)
(deny_rules, ask_rules, allow_rules)
}
/// Extract Bash-scoped patterns from a JSON array and append them to `target`.
@@ -293,31 +312,28 @@ mod tests {
let deny = vec!["git push --force".to_string()];
let ask = vec!["git push --force".to_string()];
assert_eq!(
check_command_with_rules("git push --force", &deny, &ask),
check_command_with_rules("git push --force", &deny, &ask, &[]),
PermissionVerdict::Deny
);
}
#[test]
fn test_non_bash_rules_ignored() {
// Non-Bash rules (e.g. Read, Write) must not match Bash commands.
// In load_deny_ask_rules, only Bash( rules are kept — we verify that
// extract_bash_pattern returns the original string for non-Bash rules.
assert_eq!(extract_bash_pattern("Read(**/.env*)"), "Read(**/.env*)");
// With empty rule sets (what you get after filtering out non-Bash rules),
// verdict is always Allow.
// With empty rule sets, verdict is Default (not Allow).
assert_eq!(
check_command_with_rules("cat .env", &[], &[]),
PermissionVerdict::Allow
check_command_with_rules("cat .env", &[], &[], &[]),
PermissionVerdict::Default
);
}
#[test]
fn test_empty_permissions() {
// No rules at all → Default (ask), not Allow.
assert_eq!(
check_command_with_rules("git push --force", &[], &[]),
PermissionVerdict::Allow
check_command_with_rules("git push --force", &[], &[], &[]),
PermissionVerdict::Default
);
}
@@ -348,7 +364,7 @@ mod tests {
fn test_compound_command_deny() {
let deny = vec!["git push --force".to_string()];
assert_eq!(
check_command_with_rules("git status && git push --force", &deny, &[]),
check_command_with_rules("git status && git push --force", &deny, &[], &[]),
PermissionVerdict::Deny
);
}
@@ -357,7 +373,7 @@ mod tests {
fn test_compound_command_ask() {
let ask = vec!["git push".to_string()];
assert_eq!(
check_command_with_rules("git status && git push origin main", &[], &ask),
check_command_with_rules("git status && git push origin main", &[], &ask, &[]),
PermissionVerdict::Ask
);
}
@@ -366,9 +382,8 @@ mod tests {
fn test_compound_command_deny_overrides_ask() {
let deny = vec!["git push --force".to_string()];
let ask = vec!["git status".to_string()];
// deny in compound cmd takes priority even if ask also matches a segment
assert_eq!(
check_command_with_rules("git status && git push --force", &deny, &ask),
check_command_with_rules("git status && git push --force", &deny, &ask, &[]),
PermissionVerdict::Deny
);
}
@@ -377,7 +392,7 @@ mod tests {
fn test_ask_verdict() {
let ask = vec!["git push".to_string()];
assert_eq!(
check_command_with_rules("git push origin main", &[], &ask),
check_command_with_rules("git push origin main", &[], &ask, &[]),
PermissionVerdict::Ask
);
}
@@ -441,12 +456,12 @@ mod tests {
fn test_deny_with_leading_wildcard() {
let deny = vec!["* --force".to_string()];
assert_eq!(
check_command_with_rules("git push --force", &deny, &[]),
check_command_with_rules("git push --force", &deny, &[], &[]),
PermissionVerdict::Deny
);
assert_eq!(
check_command_with_rules("git push", &deny, &[]),
PermissionVerdict::Allow
check_command_with_rules("git push", &deny, &[], &[]),
PermissionVerdict::Default
);
}
@@ -455,8 +470,66 @@ mod tests {
fn test_deny_star_colon_star() {
let deny = vec!["*:*".to_string()];
assert_eq!(
check_command_with_rules("rm -rf /", &deny, &[]),
check_command_with_rules("rm -rf /", &deny, &[], &[]),
PermissionVerdict::Deny
);
}
// --- Allow rules tests ---
#[test]
fn test_explicit_allow_rule() {
let allow = vec!["git status".to_string()];
assert_eq!(
check_command_with_rules("git status", &[], &[], &allow),
PermissionVerdict::Allow
);
}
#[test]
fn test_allow_wildcard() {
let allow = vec!["git *".to_string()];
assert_eq!(
check_command_with_rules("git log --oneline", &[], &[], &allow),
PermissionVerdict::Allow
);
}
#[test]
fn test_deny_overrides_allow() {
let deny = vec!["git push --force".to_string()];
let allow = vec!["git *".to_string()];
assert_eq!(
check_command_with_rules("git push --force", &deny, &[], &allow),
PermissionVerdict::Deny
);
}
#[test]
fn test_ask_overrides_allow() {
let ask = vec!["git push".to_string()];
let allow = vec!["git *".to_string()];
assert_eq!(
check_command_with_rules("git push origin main", &[], &ask, &allow),
PermissionVerdict::Ask
);
}
#[test]
fn test_no_rules_returns_default() {
assert_eq!(
check_command_with_rules("cargo test", &[], &[], &[]),
PermissionVerdict::Default
);
}
#[test]
fn test_default_not_allow_when_unmatched() {
// Commands not in any list should get Default, not Allow
let allow = vec!["git *".to_string()];
assert_eq!(
check_command_with_rules("cargo build", &[], &[], &allow),
PermissionVerdict::Default
);
}
}
+1 -1
View File
@@ -34,7 +34,7 @@ pub fn run(cmd: &str) -> anyhow::Result<()> {
let _ = std::io::stdout().flush();
Ok(())
}
PermissionVerdict::Ask => {
PermissionVerdict::Ask | PermissionVerdict::Default => {
print!("{}", rewritten);
let _ = std::io::stdout().flush();
std::process::exit(3);