Rewritten commands that dispatch through the fallback path skip the hook integrity check (TOML filters, args clap rejects)
hooks::integrity::runtime_check() runs only when clap parses the command into a variant listed in is_operational_command (src/lib.rs). Anything clap does not parse goes to run_fallback, which never calls it. Two kinds of command rtk rewrite emits land there:
- every rewrite target served by a TOML filter rather than a
Commandsvariant; - a listed variant whose arguments clap rejects, e.g.
docker ps x→rtk docker ps x,prisma x→rtk prisma x, and everyawscall that puts a global flag before the service (aws --profile prod s3 ls,aws --region us-east-1 ec2 describe-instances,aws --version), becauseCommands::Awstakes the service as its first positional.
With a legacy ~/.claude/hooks/rtk-rewrite.sh whose content no longer matches .rtk-hook.sha256, rtk git status exits 1 with rtk: hook integrity check FAILED, while these run the tool:
make all -> rtk make all -> make runs, exit 0
terraform plan -> rtk terraform plan -> terraform runs, exit 0
yadm x -> rtk yadm x -> yadm runs, exit 0
docker ps x -> rtk docker ps x -> docker runs, exit 0
prisma x -> rtk prisma x -> prisma runs, exit 0
aws --profile prod s3 ls -> rtk aws --profile prod s3 ls -> aws runs, exit 0
Measured on #4444's head 01738dafb and on its base 7bff768c4: one input per rewrite rule prefix (279 rewrites, 89 rtk subcommands), each run as rtk rewrite returns it, under a tampered hook, with stub tools on PATH. 231 stop at the integrity check; 48 reach the tool. 32 subcommands reach it on every input:
ansible-playbook brew bundle composer df du fail2ban-client gcloud hadolint helm iptables liquibase make markdownlint mix ping pio poetry pre-commit ps pulumi quarto rsync shellcheck sops swift systemctl terraform tofu trunk yadm yamllint
The other two, docker and prisma, reach it only on arguments clap rejects. With the hook missing, without a baseline, or with a matching baseline, every row behaves the same before and after.
The exhaustive match over Commands proposed in #4433 does not cover these, because they never become a Commands value. The drift #4433 describes is also still open: the list stays opt-in, so a new variant goes unchecked until someone lists it. A test that runs every rewrite_prefixes entry through rtk rewrite and asserts that the result reaches the check would cover both.
wshm · Automated triage by AI
🔍 Automated Triage
| 🐛 Category | bug |
| 🟠 Priority | high |
| 🎯 Confidence | 93% |
Summary
Commands dispatched via run_fallback (TOML-filter rewrites or clap-rejected args) bypass hooks::integrity::runtime_check, letting a tampered hook run 48 subcommands undetected.
📁 Relevant files
src/lib.rssrc/hooks/integrity.rs
Suggested Actions
- Move the runtime_check() call to run before dispatch (fallback vs Commands) rather than gating on is_operational_command
- Add a test iterating every rewrite_prefixes entry through
rtk rewrite, asserting it reaches integrity check (per issu… - Cross-reference #4433's exhaustive-match proposal — note it doesn't cover fallback-path commands either
- Audit Commands::Aws positional parsing so global flags before the service subcommand don't force fallback
Triaged automatically by wshm · This is an automated analysis, not a human review.
I reproduced the fallback gap on develop 5687d0d847ea and prepared the narrow patch below. It calls the existing integrity gate after RTK-owned syntax diagnostics, but before fallback can resolve a task, launch an agent, apply a TOML filter, or execute a raw command. It leaves the parsed-command allowlist unchanged.
The regression test runs eight invocation shapes under four isolated legacy-hook states (32 CLI executions), using local stub tools that record execution and exit 7. Missing hook, no baseline and matching baseline still reach the tool and preserve exit 7; a mismatching baseline exits 1 without reaching the tool. On unmodified develop the test fails because make all reaches the stub and exits 7. Five additional CLI controls preserve root help/version, init help and RTK-owned invalid-argument diagnostics.
Validation on Linux: cargo fmt --all --check, warnings-denied all-target clippy, and cargo test --all pass (5022 passed, 8 ignored). The new integration tests use the repository's isolation helper; no real cloud/database commands or installed hooks are touched. Other platforms and a live agent session were not tested.
This addresses the fallback dispatch path only. The separate request for exhaustive rewrite-prefix coverage and future typed-command drift protection remains open; this is not a claim to close all of #4672.
Apply-ready patch against 5687d0d847ea
diff --git a/src/lib.rs b/src/lib.rs
index 93e9d399..6da389bb 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1935,6 +1935,10 @@ fn run_fallback(parse_error: clap::Error) -> Result<i32> {
parse_error.exit();
}
+ // Fallbacks execute tools too, including TOML filters and typed commands
+ // whose native arguments clap rejects. Keep meta diagnostics above the gate.
+ hooks::integrity::runtime_check()?;
+
// Dynamic task subcommands: `rtk bulk-read ...` resolves from
// the active pipeline before anything falls back to raw execution.
#[cfg(feature = "engine")]
diff --git a/tests/fallback_integrity_test.rs b/tests/fallback_integrity_test.rs
new file mode 100644
index 00000000..1d7760c2
--- /dev/null
+++ b/tests/fallback_integrity_test.rs
@@ -0,0 +1,112 @@
+#![cfg(unix)]
+//! The fallback dispatcher must enforce the same legacy-hook gate as typed commands.
+mod common;
+
+use sha2::{Digest, Sha256};
+use std::os::unix::fs::PermissionsExt;
+use std::path::Path;
+use std::process::Output;
+
+fn run(root: &Path, args: &[&str]) -> Output {
+ common::rtk_command()
+ .current_dir(root)
+ .env("HOME", root)
+ .env("CLAUDE_CONFIG_DIR", root.join(".claude"))
+ .env("PATH", root.join("bin"))
+ .env("CALLED", root.join("called"))
+ .args(args)
+ .output()
+ .expect("run rtk")
+}
+
+fn sandbox(state: &str) -> tempfile::TempDir {
+ let dir = common::tempdir();
+ let root = dir.path();
+ std::fs::create_dir(root.join("bin")).expect("write isolated fixture");
+ for tool in [
+ "make",
+ "terraform",
+ "yadm",
+ "docker",
+ "prisma",
+ "aws",
+ "unknown-tool",
+ ] {
+ let path = root.join("bin").join(tool);
+ std::fs::write(
+ &path,
+ "#!/bin/sh\nprintf 'called\\n' >> \"$CALLED\"\nprintf 'stub output\\n'\nexit 7\n",
+ )
+ .expect("write isolated fixture");
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755))
+ .expect("write isolated fixture");
+ }
+ let hooks = root.join(".claude/hooks");
+ std::fs::create_dir_all(&hooks).expect("write isolated fixture");
+ let original = b"#!/bin/sh\n# original fixture\n";
+ if state != "missing" {
+ let contents: &[u8] = if state == "tampered" {
+ b"#!/bin/sh\n# modified fixture\n"
+ } else {
+ original
+ };
+ std::fs::write(hooks.join("rtk-rewrite.sh"), contents).expect("write isolated fixture");
+ }
+ if matches!(state, "verified" | "tampered") {
+ std::fs::write(
+ hooks.join(".rtk-hook.sha256"),
+ format!("{:x} rtk-rewrite.sh\n", Sha256::digest(original)),
+ )
+ .expect("write isolated fixture");
+ }
+ dir
+}
+
+#[test]
+fn fallback_checks_integrity_before_dispatch() {
+ let cases: &[&[&str]] = &[
+ &["make", "all"],
+ &["terraform", "plan"],
+ &["yadm", "x"],
+ &["docker", "ps", "x"],
+ &["prisma", "x"],
+ &["aws", "--profile", "prod", "s3", "ls"],
+ &["aws", "--version"],
+ &["unknown-tool", "arg"],
+ ];
+ for state in ["missing", "no-baseline", "verified", "tampered"] {
+ for args in cases {
+ let dir = sandbox(state);
+ let out = run(dir.path(), args);
+ let stderr = String::from_utf8_lossy(&out.stderr);
+ if state == "tampered" {
+ assert_eq!(out.status.code(), Some(1), "{args:?}: {stderr}");
+ assert!(
+ stderr.contains("hook integrity check FAILED"),
+ "{args:?}: {stderr}"
+ );
+ assert!(!dir.path().join("called").exists(), "{args:?} reached tool");
+ } else {
+ assert_eq!(out.status.code(), Some(7), "{state} {args:?}: {stderr}");
+ assert!(dir.path().join("called").exists(), "{state} {args:?}");
+ assert!(!stderr.contains("hook integrity check FAILED"));
+ }
+ }
+ }
+}
+
+#[test]
+fn fallback_preserves_meta_diagnostics_and_root_help() {
+ let dir = sandbox("tampered");
+ for args in [&["--help"][..], &["--version"], &["init", "--help"]] {
+ let out = run(dir.path(), args);
+ assert!(out.status.success(), "{args:?}");
+ assert!(!String::from_utf8_lossy(&out.stderr).contains("hook integrity check FAILED"));
+ }
+ for args in [&["gain", "--badtypo"][..], &["test", "--shell"]] {
+ let out = run(dir.path(), args);
+ assert_eq!(out.status.code(), Some(2), "{args:?}");
+ assert!(!String::from_utf8_lossy(&out.stderr).contains("hook integrity check FAILED"));
+ }
+ assert!(!dir.path().join("called").exists());
+}
@Protocol-zero-0 please open a PR with your patch. Thanks
Measured while reviewing #4713, which covers the fallback path: with a legacy hook that no longer matches its baseline, these typed commands still run the tool, on develop 690616d41 and on #4713's head, because they are not in is_operational_command:
rtk bypass make all -> make runs
rtk proxy make all -> make runs
rtk format prettier --write . -> prettier runs, while rtk prettier --write . stops
The hook does not emit them: 918 rewrites across 93 subcommands, generated from every rule's pattern, all stop at the check on #4713's head. So they only matter when typed directly or when an agent follows a hint such as rtk bypass. rtk bypass is the documented escape hatch and rtk init writes it into agent instructions, so leaving it open may be intended; the message says "RTK will not execute" either way.