hooks.rs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. use std::ffi::OsStr;
  2. use std::process::Command;
  3. use serde_json::json;
  4. use crate::config::{RuntimeFeatureConfig, RuntimeHookConfig};
  5. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  6. pub enum HookEvent {
  7. PreToolUse,
  8. PostToolUse,
  9. }
  10. impl HookEvent {
  11. fn as_str(self) -> &'static str {
  12. match self {
  13. Self::PreToolUse => "PreToolUse",
  14. Self::PostToolUse => "PostToolUse",
  15. }
  16. }
  17. }
  18. #[derive(Debug, Clone, PartialEq, Eq)]
  19. pub struct HookRunResult {
  20. denied: bool,
  21. messages: Vec<String>,
  22. }
  23. impl HookRunResult {
  24. #[must_use]
  25. pub fn allow(messages: Vec<String>) -> Self {
  26. Self {
  27. denied: false,
  28. messages,
  29. }
  30. }
  31. #[must_use]
  32. pub fn is_denied(&self) -> bool {
  33. self.denied
  34. }
  35. #[must_use]
  36. pub fn messages(&self) -> &[String] {
  37. &self.messages
  38. }
  39. }
  40. #[derive(Debug, Clone, PartialEq, Eq, Default)]
  41. pub struct HookRunner {
  42. config: RuntimeHookConfig,
  43. }
  44. impl HookRunner {
  45. #[must_use]
  46. pub fn new(config: RuntimeHookConfig) -> Self {
  47. Self { config }
  48. }
  49. #[must_use]
  50. pub fn from_feature_config(feature_config: &RuntimeFeatureConfig) -> Self {
  51. Self::new(feature_config.hooks().clone())
  52. }
  53. #[must_use]
  54. pub fn run_pre_tool_use(&self, tool_name: &str, tool_input: &str) -> HookRunResult {
  55. Self::run_commands(
  56. HookEvent::PreToolUse,
  57. self.config.pre_tool_use(),
  58. tool_name,
  59. tool_input,
  60. None,
  61. false,
  62. )
  63. }
  64. #[must_use]
  65. pub fn run_post_tool_use(
  66. &self,
  67. tool_name: &str,
  68. tool_input: &str,
  69. tool_output: &str,
  70. is_error: bool,
  71. ) -> HookRunResult {
  72. Self::run_commands(
  73. HookEvent::PostToolUse,
  74. self.config.post_tool_use(),
  75. tool_name,
  76. tool_input,
  77. Some(tool_output),
  78. is_error,
  79. )
  80. }
  81. fn run_commands(
  82. event: HookEvent,
  83. commands: &[String],
  84. tool_name: &str,
  85. tool_input: &str,
  86. tool_output: Option<&str>,
  87. is_error: bool,
  88. ) -> HookRunResult {
  89. if commands.is_empty() {
  90. return HookRunResult::allow(Vec::new());
  91. }
  92. let payload = json!({
  93. "hook_event_name": event.as_str(),
  94. "tool_name": tool_name,
  95. "tool_input": parse_tool_input(tool_input),
  96. "tool_input_json": tool_input,
  97. "tool_output": tool_output,
  98. "tool_result_is_error": is_error,
  99. })
  100. .to_string();
  101. let mut messages = Vec::new();
  102. for command in commands {
  103. match Self::run_command(
  104. command,
  105. event,
  106. tool_name,
  107. tool_input,
  108. tool_output,
  109. is_error,
  110. &payload,
  111. ) {
  112. HookCommandOutcome::Allow { message } => {
  113. if let Some(message) = message {
  114. messages.push(message);
  115. }
  116. }
  117. HookCommandOutcome::Deny { message } => {
  118. let message = message.unwrap_or_else(|| {
  119. format!("{} hook denied tool `{tool_name}`", event.as_str())
  120. });
  121. messages.push(message);
  122. return HookRunResult {
  123. denied: true,
  124. messages,
  125. };
  126. }
  127. HookCommandOutcome::Warn { message } => messages.push(message),
  128. }
  129. }
  130. HookRunResult::allow(messages)
  131. }
  132. fn run_command(
  133. command: &str,
  134. event: HookEvent,
  135. tool_name: &str,
  136. tool_input: &str,
  137. tool_output: Option<&str>,
  138. is_error: bool,
  139. payload: &str,
  140. ) -> HookCommandOutcome {
  141. let mut child = shell_command(command);
  142. child.stdin(std::process::Stdio::piped());
  143. child.stdout(std::process::Stdio::piped());
  144. child.stderr(std::process::Stdio::piped());
  145. child.env("HOOK_EVENT", event.as_str());
  146. child.env("HOOK_TOOL_NAME", tool_name);
  147. child.env("HOOK_TOOL_INPUT", tool_input);
  148. child.env("HOOK_TOOL_IS_ERROR", if is_error { "1" } else { "0" });
  149. if let Some(tool_output) = tool_output {
  150. child.env("HOOK_TOOL_OUTPUT", tool_output);
  151. }
  152. match child.output_with_stdin(payload.as_bytes()) {
  153. Ok(output) => {
  154. let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
  155. let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
  156. let message = (!stdout.is_empty()).then_some(stdout);
  157. match output.status.code() {
  158. Some(0) => HookCommandOutcome::Allow { message },
  159. Some(2) => HookCommandOutcome::Deny { message },
  160. Some(code) => HookCommandOutcome::Warn {
  161. message: format_hook_warning(
  162. command,
  163. code,
  164. message.as_deref(),
  165. stderr.as_str(),
  166. ),
  167. },
  168. None => HookCommandOutcome::Warn {
  169. message: format!(
  170. "{} hook `{command}` terminated by signal while handling `{tool_name}`",
  171. event.as_str()
  172. ),
  173. },
  174. }
  175. }
  176. Err(error) => HookCommandOutcome::Warn {
  177. message: format!(
  178. "{} hook `{command}` failed to start for `{tool_name}`: {error}",
  179. event.as_str()
  180. ),
  181. },
  182. }
  183. }
  184. }
  185. enum HookCommandOutcome {
  186. Allow { message: Option<String> },
  187. Deny { message: Option<String> },
  188. Warn { message: String },
  189. }
  190. fn parse_tool_input(tool_input: &str) -> serde_json::Value {
  191. serde_json::from_str(tool_input).unwrap_or_else(|_| json!({ "raw": tool_input }))
  192. }
  193. fn format_hook_warning(command: &str, code: i32, stdout: Option<&str>, stderr: &str) -> String {
  194. let mut message =
  195. format!("Hook `{command}` exited with status {code}; allowing tool execution to continue");
  196. if let Some(stdout) = stdout.filter(|stdout| !stdout.is_empty()) {
  197. message.push_str(": ");
  198. message.push_str(stdout);
  199. } else if !stderr.is_empty() {
  200. message.push_str(": ");
  201. message.push_str(stderr);
  202. }
  203. message
  204. }
  205. fn shell_command(command: &str) -> CommandWithStdin {
  206. #[cfg(windows)]
  207. let mut command_builder = {
  208. let mut command_builder = Command::new("cmd");
  209. command_builder.arg("/C").arg(command);
  210. CommandWithStdin::new(command_builder)
  211. };
  212. #[cfg(not(windows))]
  213. let command_builder = {
  214. let mut command_builder = Command::new("sh");
  215. command_builder.arg("-lc").arg(command);
  216. CommandWithStdin::new(command_builder)
  217. };
  218. command_builder
  219. }
  220. struct CommandWithStdin {
  221. command: Command,
  222. }
  223. impl CommandWithStdin {
  224. fn new(command: Command) -> Self {
  225. Self { command }
  226. }
  227. fn stdin(&mut self, cfg: std::process::Stdio) -> &mut Self {
  228. self.command.stdin(cfg);
  229. self
  230. }
  231. fn stdout(&mut self, cfg: std::process::Stdio) -> &mut Self {
  232. self.command.stdout(cfg);
  233. self
  234. }
  235. fn stderr(&mut self, cfg: std::process::Stdio) -> &mut Self {
  236. self.command.stderr(cfg);
  237. self
  238. }
  239. fn env<K, V>(&mut self, key: K, value: V) -> &mut Self
  240. where
  241. K: AsRef<OsStr>,
  242. V: AsRef<OsStr>,
  243. {
  244. self.command.env(key, value);
  245. self
  246. }
  247. fn output_with_stdin(&mut self, stdin: &[u8]) -> std::io::Result<std::process::Output> {
  248. let mut child = self.command.spawn()?;
  249. if let Some(mut child_stdin) = child.stdin.take() {
  250. use std::io::Write;
  251. child_stdin.write_all(stdin)?;
  252. }
  253. child.wait_with_output()
  254. }
  255. }
  256. #[cfg(test)]
  257. mod tests {
  258. use super::{HookRunResult, HookRunner};
  259. use crate::config::{RuntimeFeatureConfig, RuntimeHookConfig};
  260. #[test]
  261. fn allows_exit_code_zero_and_captures_stdout() {
  262. let runner = HookRunner::new(RuntimeHookConfig::new(
  263. vec![shell_snippet("printf 'pre ok'")],
  264. Vec::new(),
  265. ));
  266. let result = runner.run_pre_tool_use("Read", r#"{"path":"README.md"}"#);
  267. assert_eq!(result, HookRunResult::allow(vec!["pre ok".to_string()]));
  268. }
  269. #[test]
  270. fn denies_exit_code_two() {
  271. let runner = HookRunner::new(RuntimeHookConfig::new(
  272. vec![shell_snippet("printf 'blocked by hook'; exit 2")],
  273. Vec::new(),
  274. ));
  275. let result = runner.run_pre_tool_use("Bash", r#"{"command":"pwd"}"#);
  276. assert!(result.is_denied());
  277. assert_eq!(result.messages(), &["blocked by hook".to_string()]);
  278. }
  279. #[test]
  280. fn warns_for_other_non_zero_statuses() {
  281. let runner = HookRunner::from_feature_config(&RuntimeFeatureConfig::default().with_hooks(
  282. RuntimeHookConfig::new(
  283. vec![shell_snippet("printf 'warning hook'; exit 1")],
  284. Vec::new(),
  285. ),
  286. ));
  287. let result = runner.run_pre_tool_use("Edit", r#"{"file":"src/lib.rs"}"#);
  288. assert!(!result.is_denied());
  289. assert!(result
  290. .messages()
  291. .iter()
  292. .any(|message| message.contains("allowing tool execution to continue")));
  293. }
  294. #[cfg(windows)]
  295. fn shell_snippet(script: &str) -> String {
  296. script.replace('\'', "\"")
  297. }
  298. #[cfg(not(windows))]
  299. fn shell_snippet(script: &str) -> String {
  300. script.to_string()
  301. }
  302. }