| 1 | #[cfg(test)] |
| 2 | use codewhale_config::hooks::{ALL_HOOK_EVENTS, Hook, HookCondition, HookEvent, HookSteering}; |
| 3 | use codewhale_config::hooks::{HookConfigProblem, HooksConfig}; |
| 4 | use std::io::Read as _; |
| 5 | use std::path::Path; |
| 6 | |
| 7 | /// Project hook files are executable configuration and must not become an |
| 8 | /// unbounded startup allocation merely because a trusted repository supplied |
| 9 | /// a very large file. |
| 10 | const PROJECT_HOOKS_FILE_MAX_BYTES: usize = 1024 * 1024; |
| 11 | |
| 12 | pub(super) fn read_project_hooks_file(path: &Path) -> std::io::Result<String> { |
| 13 | let file = std::fs::File::open(path)?; |
| 14 | let mut contents = String::new(); |
| 15 | file.take((PROJECT_HOOKS_FILE_MAX_BYTES + 1) as u64) |
| 16 | .read_to_string(&mut contents)?; |
| 17 | if contents.len() > PROJECT_HOOKS_FILE_MAX_BYTES { |
| 18 | return Err(std::io::Error::new( |
| 19 | std::io::ErrorKind::InvalidData, |
| 20 | "project hooks file exceeds the 1 MiB limit", |
| 21 | )); |
| 22 | } |
| 23 | Ok(contents) |
| 24 | } |
| 25 | |
| 26 | /// Stable, redaction-safe one-line rendering for logs and `/hooks`. |
| 27 | #[must_use] |
| 28 | pub fn problem_summary(problem: &HookConfigProblem) -> String { |
| 29 | let disposition = if problem.rejected { |
| 30 | "rejected" |
| 31 | } else { |
| 32 | "warning" |
| 33 | }; |
| 34 | let Some(event) = problem.event else { |
| 35 | return format!("{disposition}: `[hooks]` setting — {}", problem.detail); |
| 36 | }; |
| 37 | // The name is operator-supplied and lands in `/hooks list` and the |
| 38 | // tracing stream; bound it and strip control characters here rather |
| 39 | // than trusting every caller to remember. |
| 40 | let label = super::executor::sanitize_hook_label(problem.name.as_deref()); |
| 41 | format!( |
| 42 | "{disposition}: `{}` hook `{label}` — {}", |
| 43 | event.as_str(), |
| 44 | problem.detail |
| 45 | ) |
| 46 | } |
| 47 | |
| 48 | /// Seed for a workspace's `.codewhale/hooks.toml` when it does not exist yet. |
| 49 | /// |
| 50 | /// Entirely commented out: creating the file must never change behaviour, and |
| 51 | /// an empty file that teaches the schema beats an empty file that does not. |
| 52 | /// The event list here is the one `/hooks events` prints. |
| 53 | pub const PROJECT_HOOKS_TEMPLATE: &str = r#"# Codewhale project hooks. |
| 54 | # |
| 55 | # Hooks are executable repository configuration: they run only after this |
| 56 | # workspace is trusted and these exact bytes approved (`/hooks review`, then |
| 57 | # `/hooks approve <digest>`). Global hooks live in the `[hooks]` |
| 58 | # table of your own config.toml; the entries here are appended after those. |
| 59 | # |
| 60 | # Run `/hooks events` in Codewhale for the full event list with descriptions. |
| 61 | # |
| 62 | # Uncomment to try one: |
| 63 | # |
| 64 | # [[hooks]] |
| 65 | # name = "format on write" |
| 66 | # event = "post_tool_use" |
| 67 | # command = "cargo fmt --all" |
| 68 | # timeout_secs = 30 |
| 69 | # background = true |
| 70 | # continue_on_error = true |
| 71 | "#; |
| 72 | |
| 73 | /// Load global hooks merged with project-local `.codewhale/hooks.toml` (#3026). |
| 74 | /// |
| 75 | /// Project hooks are executable repository configuration, so they are only |
| 76 | /// honored after workspace trust and exact-byte hook approval in user config. |
| 77 | /// Trusted project hooks are appended after global hooks. A malformed |
| 78 | /// trusted project file logs a warning and falls back to global-only. |
| 79 | #[cfg(any(test, feature = "test-support"))] |
| 80 | pub fn load_with_project(global: HooksConfig, workspace: &Path) -> HooksConfig { |
| 81 | load_with_project_and_plugins(global, workspace, None) |
| 82 | } |
| 83 | |
| 84 | /// Merge global, reviewed plugin, then trusted project hooks. |
| 85 | /// |
| 86 | /// Project hooks intentionally remain last because that is the existing |
| 87 | /// tie-breaking contract for mutable `message_submit` transformations. |
| 88 | /// Plugin files are read only from Codewhale's immutable staged snapshot; |
| 89 | /// their attached authority is rechecked at every process-spawn boundary. |
| 90 | pub fn load_with_project_and_plugins( |
| 91 | global: HooksConfig, |
| 92 | workspace: &Path, |
| 93 | plugins: Option<&codewhale_plugins::PluginRegistry>, |
| 94 | ) -> HooksConfig { |
| 95 | let mut merged = global; |
| 96 | if let Some(plugins) = plugins { |
| 97 | let (sources, adapter_errors) = codewhale_plugins::runtime::active_component_sources( |
| 98 | plugins, |
| 99 | codewhale_plugins::activation::PluginActivationCapability::Hooks, |
| 100 | ); |
| 101 | for error in adapter_errors { |
| 102 | merged.problems.push(HookConfigProblem { |
| 103 | name: None, |
| 104 | event: None, |
| 105 | detail: error, |
| 106 | rejected: true, |
| 107 | }); |
| 108 | } |
| 109 | for source in sources { |
| 110 | match load_plugin_hook_component(&source.path, &source.authority) { |
| 111 | Ok(mut plugin) => { |
| 112 | merged.problems.append(&mut plugin.problems); |
| 113 | merged.hooks.append(&mut plugin.hooks); |
| 114 | } |
| 115 | Err(error) => merged.problems.push(HookConfigProblem { |
| 116 | name: Some(source.plugin_name), |
| 117 | event: None, |
| 118 | detail: error, |
| 119 | rejected: true, |
| 120 | }), |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | let project_path = workspace.join(".codewhale").join("hooks.toml"); |
| 125 | if project_path.symlink_metadata().is_ok() { |
| 126 | match super::authority::approved_project_hooks(workspace) { |
| 127 | Ok((authority, contents)) => match toml::from_str::<HooksConfig>(&contents) { |
| 128 | Ok(mut project) => { |
| 129 | for hook in &mut project.hooks { |
| 130 | hook.project_authority = Some(authority.clone()); |
| 131 | } |
| 132 | merged.hooks.extend(project.hooks); |
| 133 | } |
| 134 | Err(_) => merged.problems.push(HookConfigProblem { |
| 135 | name: None, |
| 136 | event: None, |
| 137 | detail: "Invalid project hooks TOML; project hooks were not loaded".into(), |
| 138 | rejected: true, |
| 139 | }), |
| 140 | }, |
| 141 | Err(detail) => merged.problems.push(HookConfigProblem { |
| 142 | name: None, |
| 143 | event: None, |
| 144 | detail, |
| 145 | rejected: true, |
| 146 | }), |
| 147 | } |
| 148 | } |
| 149 | // Validation runs on every path, not just the project-hooks path, so a |
| 150 | // globally-configured hook that can never match is rejected too. |
| 151 | apply_validation(&mut merged); |
| 152 | merged |
| 153 | } |
| 154 | |
| 155 | /// Run [`HooksConfig::validate_indexed`], drop every rejected hook, and record the |
| 156 | /// problems so `/hooks` and the logs can show them. |
| 157 | /// |
| 158 | /// Rejection is by position, so a broken entry never takes an innocent one |
| 159 | /// with it just because the two share a name (or share the absence of one). |
| 160 | fn apply_validation(config: &mut HooksConfig) { |
| 161 | let inherited_problems = std::mem::take(&mut config.problems); |
| 162 | let setting_problems = config.validate_settings(); |
| 163 | // Reject the value, not just report it: the executor reads |
| 164 | // `default_timeout_secs` directly, so leaving `Some(0)` in place would |
| 165 | // make the warning cosmetic. |
| 166 | if setting_problems.iter().any(|p| p.rejected) { |
| 167 | config.default_timeout_secs = config.default_timeout_secs.filter(|secs| *secs > 0); |
| 168 | } |
| 169 | let problems = config.validate_indexed(); |
| 170 | for problem in setting_problems |
| 171 | .iter() |
| 172 | .chain(problems.iter().map(|(_, p)| p)) |
| 173 | { |
| 174 | tracing::warn!(target: "hooks", "{}", problem_summary(problem)); |
| 175 | } |
| 176 | let rejected: std::collections::HashSet<usize> = problems |
| 177 | .iter() |
| 178 | .filter(|(_, problem)| problem.rejected) |
| 179 | .map(|(index, _)| *index) |
| 180 | .collect(); |
| 181 | if !rejected.is_empty() { |
| 182 | let mut index = 0; |
| 183 | config.hooks.retain(|_| { |
| 184 | let keep = !rejected.contains(&index); |
| 185 | index += 1; |
| 186 | keep |
| 187 | }); |
| 188 | } |
| 189 | config.problems = inherited_problems |
| 190 | .into_iter() |
| 191 | .chain(setting_problems) |
| 192 | .chain(problems.into_iter().map(|(_, problem)| problem)) |
| 193 | .collect(); |
| 194 | } |
| 195 | |
| 196 | fn load_plugin_hook_component( |
| 197 | component: &Path, |
| 198 | authority: &codewhale_config::PluginAuthority, |
| 199 | ) -> Result<HooksConfig, String> { |
| 200 | let mut paths = if component.is_file() { |
| 201 | vec![component.to_path_buf()] |
| 202 | } else if component.is_dir() { |
| 203 | let mut paths = std::fs::read_dir(component) |
| 204 | .map_err(|error| format!("failed to read plugin Hooks component: {error}"))? |
| 205 | .filter_map(Result::ok) |
| 206 | .map(|entry| entry.path()) |
| 207 | .filter(|path| path.extension().and_then(|value| value.to_str()) == Some("toml")) |
| 208 | .collect::<Vec<_>>(); |
| 209 | paths.sort(); |
| 210 | paths |
| 211 | } else { |
| 212 | return Err("plugin Hooks component is unavailable".to_string()); |
| 213 | }; |
| 214 | if paths.is_empty() { |
| 215 | return Err("plugin Hooks component contains no TOML configuration".to_string()); |
| 216 | } |
| 217 | |
| 218 | let mut merged = HooksConfig::default(); |
| 219 | for path in paths.drain(..) { |
| 220 | let contents = read_project_hooks_file(&path) |
| 221 | .map_err(|error| format!("failed to read plugin Hooks file: {error}"))?; |
| 222 | let mut parsed: HooksConfig = toml::from_str(&contents) |
| 223 | .map_err(|error| format!("failed to parse plugin Hooks file: {error}"))?; |
| 224 | if parsed.working_dir.is_some() { |
| 225 | return Err( |
| 226 | "plugin Hooks may not set working_dir; hooks run in the active workspace" |
| 227 | .to_string(), |
| 228 | ); |
| 229 | } |
| 230 | apply_validation(&mut parsed); |
| 231 | if !parsed.enabled { |
| 232 | continue; |
| 233 | } |
| 234 | if let Some(timeout) = parsed.default_timeout_secs.filter(|value| *value > 0) { |
| 235 | for hook in &mut parsed.hooks { |
| 236 | hook.timeout_secs = timeout; |
| 237 | } |
| 238 | } |
| 239 | for hook in &mut parsed.hooks { |
| 240 | hook.plugin_authority = Some(authority.clone()); |
| 241 | } |
| 242 | merged.problems.append(&mut parsed.problems); |
| 243 | merged.hooks.append(&mut parsed.hooks); |
| 244 | } |
| 245 | Ok(merged) |
| 246 | } |
| 247 | |
| 248 | pub fn workspace_allows_project_hooks(workspace: &Path) -> bool { |
| 249 | super::authority::approved_project_hooks(workspace).is_ok() |
| 250 | } |
| 251 | |
| 252 | #[cfg(test)] |
| 253 | mod contract_tests { |
| 254 | use super::*; |
| 255 | |
| 256 | /// The sixteen event names are a public contract: they appear in |
| 257 | /// `config.toml`, in `/hooks events`, and in `docs/HOOKS.md`. A rename is |
| 258 | /// a breaking change, and a new variant must be added deliberately. |
| 259 | #[test] |
| 260 | fn all_sixteen_event_names_are_stable_and_exhaustive() { |
| 261 | let names: Vec<&str> = ALL_HOOK_EVENTS.iter().map(|e| e.as_str()).collect(); |
| 262 | assert_eq!( |
| 263 | names, |
| 264 | vec![ |
| 265 | "session_start", |
| 266 | "session_end", |
| 267 | "turn_end", |
| 268 | "message_submit", |
| 269 | "tool_call_before", |
| 270 | "tool_call_after", |
| 271 | "mode_change", |
| 272 | "on_error", |
| 273 | "subagent_spawn", |
| 274 | "subagent_complete", |
| 275 | "shell_env", |
| 276 | "session_idle", |
| 277 | "session_error", |
| 278 | "waiting_for_user", |
| 279 | "session_busy", |
| 280 | "pre_compact", |
| 281 | ] |
| 282 | ); |
| 283 | |
| 284 | // Exhaustiveness: every variant appears exactly once. The `match` here |
| 285 | // fails to compile if a variant is added without updating the list. |
| 286 | for event in ALL_HOOK_EVENTS { |
| 287 | let covered = match event { |
| 288 | HookEvent::SessionStart |
| 289 | | HookEvent::SessionEnd |
| 290 | | HookEvent::TurnEnd |
| 291 | | HookEvent::MessageSubmit |
| 292 | | HookEvent::ToolCallBefore |
| 293 | | HookEvent::ToolCallAfter |
| 294 | | HookEvent::ModeChange |
| 295 | | HookEvent::OnError |
| 296 | | HookEvent::SubagentSpawn |
| 297 | | HookEvent::SubagentComplete |
| 298 | | HookEvent::ShellEnv |
| 299 | | HookEvent::SessionIdle |
| 300 | | HookEvent::SessionError |
| 301 | | HookEvent::WaitingForUser |
| 302 | | HookEvent::SessionBusy |
| 303 | | HookEvent::PreCompact => true, |
| 304 | }; |
| 305 | assert!(covered); |
| 306 | } |
| 307 | let unique: std::collections::HashSet<&str> = names.iter().copied().collect(); |
| 308 | assert_eq!(unique.len(), 16); |
| 309 | } |
| 310 | |
| 311 | /// Serde round-trip for every event name, in the exact `event = "..."` |
| 312 | /// spelling users write in `config.toml`. |
| 313 | #[test] |
| 314 | fn every_event_name_round_trips_through_serde() { |
| 315 | for event in ALL_HOOK_EVENTS { |
| 316 | let json = serde_json::to_string(&event).expect("serialize"); |
| 317 | assert_eq!(json, format!("\"{}\"", event.as_str())); |
| 318 | let parsed: HookEvent = serde_json::from_str(&json).expect("deserialize"); |
| 319 | assert_eq!(parsed, event); |
| 320 | |
| 321 | let toml_src = format!("event = \"{}\"\ncommand = \"true\"\n", event.as_str()); |
| 322 | let hook: Hook = toml::from_str(&toml_src).expect("hook parses from minimal toml"); |
| 323 | assert_eq!(hook.event, event); |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | /// Backward compatibility: a pre-existing hook table with only the two |
| 328 | /// required keys still parses, and the defaults are the documented ones. |
| 329 | #[test] |
| 330 | fn minimal_hook_toml_keeps_its_documented_defaults() { |
| 331 | let hook: Hook = toml::from_str( |
| 332 | r#" |
| 333 | event = "session_start" |
| 334 | command = "echo hi" |
| 335 | "#, |
| 336 | ) |
| 337 | .expect("parse"); |
| 338 | assert_eq!(hook.timeout_secs, 30); |
| 339 | assert!(!hook.background); |
| 340 | assert!(hook.continue_on_error); |
| 341 | assert!(hook.condition.is_none()); |
| 342 | assert!(hook.name.is_none()); |
| 343 | } |
| 344 | |
| 345 | /// `problems` is runtime-only state. It must never appear in a serialized |
| 346 | /// config, and its absence must not break deserialization. |
| 347 | #[test] |
| 348 | fn config_problems_are_not_part_of_the_serialized_config() { |
| 349 | let config = HooksConfig { |
| 350 | enabled: true, |
| 351 | hooks: vec![Hook::new(HookEvent::SessionStart, "true")], |
| 352 | problems: vec![HookConfigProblem { |
| 353 | name: Some("x".to_string()), |
| 354 | event: Some(HookEvent::SessionStart), |
| 355 | detail: "example".to_string(), |
| 356 | rejected: true, |
| 357 | }], |
| 358 | ..HooksConfig::default() |
| 359 | }; |
| 360 | let serialized = serde_json::to_string(&config).expect("serialize"); |
| 361 | assert!(!serialized.contains("problems"), "{serialized}"); |
| 362 | assert!(!serialized.contains("example"), "{serialized}"); |
| 363 | |
| 364 | let reparsed: HooksConfig = serde_json::from_str(&serialized).expect("reparse"); |
| 365 | assert!(reparsed.problems.is_empty()); |
| 366 | assert_eq!(reparsed.hooks.len(), 1); |
| 367 | |
| 368 | // And a config that predates the field still deserializes. |
| 369 | let legacy: HooksConfig = toml::from_str( |
| 370 | r#" |
| 371 | enabled = true |
| 372 | |
| 373 | [[hooks]] |
| 374 | event = "session_start" |
| 375 | command = "echo hi" |
| 376 | "#, |
| 377 | ) |
| 378 | .expect("legacy config parses"); |
| 379 | assert!(legacy.problems.is_empty()); |
| 380 | assert_eq!(legacy.hooks.len(), 1); |
| 381 | } |
| 382 | |
| 383 | /// The steering allowlist. Exactly three events can change what Codewhale |
| 384 | /// does; every other event defaults to observer. |
| 385 | #[test] |
| 386 | fn steering_allowlist_is_exactly_three_events() { |
| 387 | let steering: Vec<&str> = ALL_HOOK_EVENTS |
| 388 | .iter() |
| 389 | .filter(|e| e.can_steer()) |
| 390 | .map(|e| e.as_str()) |
| 391 | .collect(); |
| 392 | assert_eq!( |
| 393 | steering, |
| 394 | vec!["message_submit", "tool_call_before", "shell_env"] |
| 395 | ); |
| 396 | |
| 397 | assert_eq!( |
| 398 | HookEvent::MessageSubmit.steering(), |
| 399 | HookSteering::TransformsSubmittedText |
| 400 | ); |
| 401 | assert_eq!( |
| 402 | HookEvent::ToolCallBefore.steering(), |
| 403 | HookSteering::DecidesToolCall |
| 404 | ); |
| 405 | assert_eq!( |
| 406 | HookEvent::ShellEnv.steering(), |
| 407 | HookSteering::ContributesShellEnv |
| 408 | ); |
| 409 | |
| 410 | for event in ALL_HOOK_EVENTS { |
| 411 | if !steering.contains(&event.as_str()) { |
| 412 | assert_eq!( |
| 413 | event.steering(), |
| 414 | HookSteering::Observer, |
| 415 | "`{}` must default to observer", |
| 416 | event.as_str() |
| 417 | ); |
| 418 | } |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | /// Observer-only is a claim about Codewhale's control flow, not about the |
| 423 | /// command. This test exists so the distinction is written down somewhere |
| 424 | /// executable: an observer hook is still an arbitrary shell command and |
| 425 | /// its external side effects are entirely real. |
| 426 | #[test] |
| 427 | fn observer_only_still_runs_a_real_command_with_real_side_effects() { |
| 428 | let dir = tempfile::tempdir().expect("tempdir"); |
| 429 | let marker = dir.path().join("observer-side-effect.txt"); |
| 430 | assert!(!marker.exists()); |
| 431 | |
| 432 | let command = if cfg!(windows) { |
| 433 | format!("echo touched> {}", marker.display()) |
| 434 | } else { |
| 435 | format!("echo touched > {}", marker.display()) |
| 436 | }; |
| 437 | let executor = crate::hooks::HookExecutor::new( |
| 438 | HooksConfig { |
| 439 | enabled: true, |
| 440 | hooks: vec![Hook::new(HookEvent::SessionEnd, &command).with_name("observer")], |
| 441 | ..HooksConfig::default() |
| 442 | }, |
| 443 | dir.path().to_path_buf(), |
| 444 | ); |
| 445 | |
| 446 | let results = executor.execute( |
| 447 | HookEvent::SessionEnd, |
| 448 | &crate::hooks::HookContext::new().with_session_id("sess_test"), |
| 449 | ); |
| 450 | |
| 451 | // Codewhale ignored the result... |
| 452 | assert_eq!(results.len(), 1); |
| 453 | assert_eq!(HookEvent::SessionEnd.steering(), HookSteering::Observer); |
| 454 | // ...and the command still changed the filesystem. |
| 455 | assert!( |
| 456 | marker.exists(), |
| 457 | "an observer hook is not side-effect free; it just cannot steer" |
| 458 | ); |
| 459 | } |
| 460 | |
| 461 | #[test] |
| 462 | fn exit_code_conditions_are_rejected_only_where_no_exit_code_exists() { |
| 463 | for event in ALL_HOOK_EVENTS { |
| 464 | let config = HooksConfig { |
| 465 | enabled: true, |
| 466 | hooks: vec![ |
| 467 | Hook::new(event, "true") |
| 468 | .with_name("gate") |
| 469 | .with_condition(HookCondition::ExitCode { code: 1 }), |
| 470 | ], |
| 471 | ..HooksConfig::default() |
| 472 | }; |
| 473 | let problems = config.validate(); |
| 474 | if event.provides_exit_code() { |
| 475 | assert!( |
| 476 | problems.is_empty(), |
| 477 | "`{}` should accept an exit_code condition: {problems:?}", |
| 478 | event.as_str() |
| 479 | ); |
| 480 | } else { |
| 481 | assert!( |
| 482 | problems.iter().any(|p| p.rejected), |
| 483 | "`{}` must reject an exit_code condition", |
| 484 | event.as_str() |
| 485 | ); |
| 486 | } |
| 487 | } |
| 488 | assert!(HookEvent::ToolCallAfter.provides_exit_code()); |
| 489 | // `on_error` fires for tool failures with the tool name, call id, and |
| 490 | // reported exit code attached (`tui/tool_routing.rs`), so scoping an |
| 491 | // `on_error` hook by tool or exit code is a supported configuration — |
| 492 | // it used to be rejected at load while the runtime and docs both |
| 493 | // promised those fields. |
| 494 | assert!(HookEvent::OnError.provides_exit_code()); |
| 495 | assert!(HookEvent::OnError.provides_tool_identity()); |
| 496 | } |
| 497 | |
| 498 | /// A tool-scoped `on_error` hook — the shape `docs/HOOKS.md` documents and |
| 499 | /// `tool_routing.rs` supplies context for — must survive load intact. |
| 500 | #[test] |
| 501 | fn tool_scoped_on_error_hooks_load_and_dispatch() { |
| 502 | let dir = tempfile::tempdir().expect("tempdir"); |
| 503 | let global = HooksConfig { |
| 504 | enabled: true, |
| 505 | hooks: vec![ |
| 506 | Hook::new(HookEvent::OnError, "notify.sh") |
| 507 | .with_name("shell-failure") |
| 508 | .with_condition(HookCondition::All { |
| 509 | conditions: vec![ |
| 510 | HookCondition::ToolName { |
| 511 | name: "exec_shell".to_string(), |
| 512 | }, |
| 513 | HookCondition::ExitCode { code: 127 }, |
| 514 | ], |
| 515 | }), |
| 516 | ], |
| 517 | ..HooksConfig::default() |
| 518 | }; |
| 519 | |
| 520 | let loaded = load_with_project(global, dir.path()); |
| 521 | |
| 522 | assert_eq!(loaded.hooks.len(), 1, "{:?}", loaded.problems); |
| 523 | assert!( |
| 524 | loaded.problems.iter().all(|p| !p.rejected), |
| 525 | "{:?}", |
| 526 | loaded.problems |
| 527 | ); |
| 528 | assert_eq!(loaded.hooks_for_event(HookEvent::OnError).len(), 1); |
| 529 | } |
| 530 | |
| 531 | /// A Windows crash code such as `0xC0000005` does not fit in `i32`. The |
| 532 | /// predicate has to hold it, or the hook silently never matches. |
| 533 | #[test] |
| 534 | fn exit_code_conditions_hold_large_windows_crash_codes() { |
| 535 | let hook: Hook = toml::from_str( |
| 536 | r#" |
| 537 | event = "tool_call_after" |
| 538 | command = "echo crashed" |
| 539 | condition = { type = "exit_code", code = 3221225477 } |
| 540 | "#, |
| 541 | ) |
| 542 | .expect("large exit code parses"); |
| 543 | assert!(matches!( |
| 544 | hook.condition, |
| 545 | Some(HookCondition::ExitCode { |
| 546 | code: 3_221_225_477 |
| 547 | }) |
| 548 | )); |
| 549 | |
| 550 | // Old, small values keep parsing exactly as before. |
| 551 | let legacy: Hook = toml::from_str( |
| 552 | r#" |
| 553 | event = "tool_call_after" |
| 554 | command = "echo failed" |
| 555 | condition = { type = "exit_code", code = 1 } |
| 556 | "#, |
| 557 | ) |
| 558 | .expect("small exit code still parses"); |
| 559 | assert!(matches!( |
| 560 | legacy.condition, |
| 561 | Some(HookCondition::ExitCode { code: 1 }) |
| 562 | )); |
| 563 | } |
| 564 | |
| 565 | /// Rejection is per entry. One broken hook must not delete the hooks that |
| 566 | /// merely share its name — or share its lack of one. |
| 567 | #[test] |
| 568 | fn rejection_drops_only_the_offending_entry() { |
| 569 | let dir = tempfile::tempdir().expect("tempdir"); |
| 570 | let global = HooksConfig { |
| 571 | enabled: true, |
| 572 | hooks: vec![ |
| 573 | // Two unnamed `session_start` entries; only the second is |
| 574 | // invalid (an `exit_code` predicate that can never match). |
| 575 | Hook::new(HookEvent::SessionStart, "echo innocent-unnamed"), |
| 576 | Hook::new(HookEvent::SessionStart, "echo broken-unnamed") |
| 577 | .with_condition(HookCondition::ExitCode { code: 0 }), |
| 578 | // Two hooks sharing the name `gate`; only the second is empty. |
| 579 | Hook::new(HookEvent::ToolCallBefore, "echo innocent-gate").with_name("gate"), |
| 580 | Hook::new(HookEvent::ToolCallBefore, " ").with_name("gate"), |
| 581 | ], |
| 582 | ..HooksConfig::default() |
| 583 | }; |
| 584 | |
| 585 | let loaded = load_with_project(global, dir.path()); |
| 586 | |
| 587 | let surviving: Vec<&str> = loaded.hooks.iter().map(|h| h.command.as_str()).collect(); |
| 588 | assert_eq!( |
| 589 | surviving, |
| 590 | vec!["echo innocent-unnamed", "echo innocent-gate"], |
| 591 | "an invalid entry took an innocent same-identity entry with it" |
| 592 | ); |
| 593 | assert_eq!( |
| 594 | loaded.problems.iter().filter(|p| p.rejected).count(), |
| 595 | 2, |
| 596 | "{:?}", |
| 597 | loaded.problems |
| 598 | ); |
| 599 | assert_eq!(loaded.hooks_for_event(HookEvent::SessionStart).len(), 1); |
| 600 | assert_eq!(loaded.hooks_for_event(HookEvent::ToolCallBefore).len(), 1); |
| 601 | } |
| 602 | |
| 603 | #[test] |
| 604 | fn effective_timeout_reports_the_global_override() { |
| 605 | let hook = Hook::new(HookEvent::SessionStart, "true").with_timeout(90); |
| 606 | |
| 607 | let per_hook = HooksConfig::default(); |
| 608 | assert_eq!(per_hook.effective_timeout_secs(&hook), 90); |
| 609 | assert!(!per_hook.timeout_is_overridden()); |
| 610 | |
| 611 | let overridden = HooksConfig { |
| 612 | default_timeout_secs: Some(5), |
| 613 | ..HooksConfig::default() |
| 614 | }; |
| 615 | assert_eq!(overridden.effective_timeout_secs(&hook), 5); |
| 616 | assert!(overridden.timeout_is_overridden()); |
| 617 | } |
| 618 | |
| 619 | /// `timeout_secs = 0` was rejected per hook, but the override that |
| 620 | /// *replaces* every hook's value was not checked at all — so a single |
| 621 | /// `default_timeout_secs = 0` killed every hook before it could speak, |
| 622 | /// including `tool_call_before` gates that then fail closed on every call. |
| 623 | #[test] |
| 624 | fn zero_default_timeout_is_rejected_and_ignored() { |
| 625 | let hook = Hook::new(HookEvent::SessionStart, "true").with_timeout(90); |
| 626 | let zeroed = HooksConfig { |
| 627 | enabled: true, |
| 628 | hooks: vec![hook.clone()], |
| 629 | default_timeout_secs: Some(0), |
| 630 | ..HooksConfig::default() |
| 631 | }; |
| 632 | |
| 633 | let problems = zeroed.validate(); |
| 634 | let problem = problems |
| 635 | .iter() |
| 636 | .find(|p| p.detail.contains("default_timeout_secs")) |
| 637 | .expect("zero override reported"); |
| 638 | assert!(problem.rejected, "{problem:?}"); |
| 639 | assert!( |
| 640 | problem.event.is_none(), |
| 641 | "the override is not one hook's problem: {problem:?}" |
| 642 | ); |
| 643 | assert!(problem_summary(problem).contains("`[hooks]` setting")); |
| 644 | |
| 645 | // Even unvalidated, the accessors refuse the value rather than hand a |
| 646 | // zero budget to the executor. |
| 647 | assert_eq!(zeroed.effective_timeout_secs(&hook), 90); |
| 648 | assert!(!zeroed.timeout_is_overridden()); |
| 649 | } |
| 650 | |
| 651 | /// The load path must strip the value, not merely warn about it: the |
| 652 | /// executor reads `default_timeout_secs` and the hook itself is innocent, |
| 653 | /// so it has to survive. |
| 654 | #[test] |
| 655 | fn zero_default_timeout_is_stripped_at_load_and_the_hook_survives() { |
| 656 | let dir = tempfile::tempdir().expect("tempdir"); |
| 657 | let global = HooksConfig { |
| 658 | enabled: true, |
| 659 | hooks: vec![ |
| 660 | Hook::new(HookEvent::SessionStart, "true") |
| 661 | .with_name("greet") |
| 662 | .with_timeout(90), |
| 663 | ], |
| 664 | default_timeout_secs: Some(0), |
| 665 | ..HooksConfig::default() |
| 666 | }; |
| 667 | |
| 668 | let loaded = load_with_project(global, dir.path()); |
| 669 | assert_eq!(loaded.default_timeout_secs, None, "override not stripped"); |
| 670 | assert_eq!(loaded.hooks.len(), 1, "the hook itself was not at fault"); |
| 671 | assert_eq!(loaded.effective_timeout_secs(&loaded.hooks[0]), 90); |
| 672 | assert!( |
| 673 | loaded |
| 674 | .problems |
| 675 | .iter() |
| 676 | .any(|p| p.rejected && p.event.is_none()), |
| 677 | "{:?}", |
| 678 | loaded.problems |
| 679 | ); |
| 680 | } |
| 681 | |
| 682 | /// A positive override still loads untouched — the rejection is for zero |
| 683 | /// only, not a general distrust of the setting. |
| 684 | #[test] |
| 685 | fn positive_default_timeout_survives_load() { |
| 686 | let dir = tempfile::tempdir().expect("tempdir"); |
| 687 | let loaded = load_with_project( |
| 688 | HooksConfig { |
| 689 | enabled: true, |
| 690 | hooks: vec![Hook::new(HookEvent::SessionStart, "true").with_timeout(90)], |
| 691 | default_timeout_secs: Some(5), |
| 692 | ..HooksConfig::default() |
| 693 | }, |
| 694 | dir.path(), |
| 695 | ); |
| 696 | assert_eq!(loaded.default_timeout_secs, Some(5)); |
| 697 | assert!(loaded.timeout_is_overridden()); |
| 698 | assert_eq!(loaded.effective_timeout_secs(&loaded.hooks[0]), 5); |
| 699 | assert!(loaded.problems.is_empty(), "{:?}", loaded.problems); |
| 700 | } |
| 701 | |
| 702 | /// Names are operator text and reach `/hooks list` and the tracing stream. |
| 703 | #[test] |
| 704 | fn problem_summaries_bound_and_defang_the_hook_name() { |
| 705 | let problem = HookConfigProblem { |
| 706 | name: Some(format!("\u{1b}[2Jgate\n{}", "n".repeat(500))), |
| 707 | event: Some(HookEvent::ToolCallBefore), |
| 708 | detail: "example detail".to_string(), |
| 709 | rejected: true, |
| 710 | }; |
| 711 | let summary = problem_summary(&problem); |
| 712 | assert!(!summary.contains('\u{1b}'), "{summary}"); |
| 713 | assert!(!summary.contains('\n'), "{summary}"); |
| 714 | assert!(summary.contains("gate"), "{summary}"); |
| 715 | assert!( |
| 716 | summary.chars().count() < 200, |
| 717 | "unbounded summary: {} chars", |
| 718 | summary.chars().count() |
| 719 | ); |
| 720 | } |
| 721 | |
| 722 | #[test] |
| 723 | fn mode_conditions_are_rejected_on_shell_env_only() { |
| 724 | for event in ALL_HOOK_EVENTS { |
| 725 | let config = HooksConfig { |
| 726 | enabled: true, |
| 727 | hooks: vec![ |
| 728 | Hook::new(event, "true").with_condition(HookCondition::Mode { |
| 729 | mode: "plan".to_string(), |
| 730 | }), |
| 731 | ], |
| 732 | ..HooksConfig::default() |
| 733 | }; |
| 734 | let rejected = config.validate().iter().any(|p| p.rejected); |
| 735 | assert_eq!( |
| 736 | rejected, |
| 737 | matches!(event, HookEvent::ShellEnv), |
| 738 | "unexpected mode-condition disposition for `{}`", |
| 739 | event.as_str() |
| 740 | ); |
| 741 | } |
| 742 | } |
| 743 | |
| 744 | #[test] |
| 745 | fn tool_conditions_are_rejected_on_events_with_no_tool() { |
| 746 | for event in ALL_HOOK_EVENTS { |
| 747 | for condition in [ |
| 748 | HookCondition::ToolName { |
| 749 | name: "exec_shell".to_string(), |
| 750 | }, |
| 751 | HookCondition::ToolCategory { |
| 752 | category: "shell".to_string(), |
| 753 | }, |
| 754 | ] { |
| 755 | let config = HooksConfig { |
| 756 | enabled: true, |
| 757 | hooks: vec![Hook::new(event, "true").with_condition(condition)], |
| 758 | ..HooksConfig::default() |
| 759 | }; |
| 760 | let rejected = config.validate().iter().any(|p| p.rejected); |
| 761 | assert_eq!( |
| 762 | rejected, |
| 763 | !event.provides_tool_identity(), |
| 764 | "unexpected tool-condition disposition for `{}`", |
| 765 | event.as_str() |
| 766 | ); |
| 767 | } |
| 768 | } |
| 769 | } |
| 770 | |
| 771 | #[test] |
| 772 | fn unsupported_conditions_nested_in_combinators_are_still_rejected() { |
| 773 | let config = HooksConfig { |
| 774 | enabled: true, |
| 775 | hooks: vec![ |
| 776 | Hook::new(HookEvent::SessionStart, "true") |
| 777 | .with_name("sneaky") |
| 778 | .with_condition(HookCondition::Any { |
| 779 | conditions: vec![ |
| 780 | HookCondition::Always, |
| 781 | HookCondition::All { |
| 782 | conditions: vec![HookCondition::ExitCode { code: 0 }], |
| 783 | }, |
| 784 | ], |
| 785 | }), |
| 786 | ], |
| 787 | ..HooksConfig::default() |
| 788 | }; |
| 789 | let problems = config.validate(); |
| 790 | assert!( |
| 791 | problems.iter().any(|p| p.rejected), |
| 792 | "a nested unsupported predicate must not hide behind a combinator" |
| 793 | ); |
| 794 | } |
| 795 | |
| 796 | #[test] |
| 797 | fn rejected_hooks_are_dropped_at_load_and_reported() { |
| 798 | let dir = tempfile::tempdir().expect("tempdir"); |
| 799 | let global = HooksConfig { |
| 800 | enabled: true, |
| 801 | hooks: vec![ |
| 802 | Hook::new(HookEvent::SessionStart, "echo ok").with_name("good"), |
| 803 | Hook::new(HookEvent::SessionStart, "echo never") |
| 804 | .with_name("inert") |
| 805 | .with_condition(HookCondition::ExitCode { code: 0 }), |
| 806 | ], |
| 807 | ..HooksConfig::default() |
| 808 | }; |
| 809 | |
| 810 | let loaded = load_with_project(global, dir.path()); |
| 811 | |
| 812 | assert_eq!( |
| 813 | loaded.hooks.len(), |
| 814 | 1, |
| 815 | "the inert hook must not survive load" |
| 816 | ); |
| 817 | assert_eq!(loaded.hooks[0].name.as_deref(), Some("good")); |
| 818 | assert!(loaded.problems.iter().any(|p| p.rejected)); |
| 819 | // It is also invisible to dispatch, not merely to the listing. |
| 820 | assert_eq!(loaded.hooks_for_event(HookEvent::SessionStart).len(), 1); |
| 821 | } |
| 822 | |
| 823 | #[test] |
| 824 | fn empty_command_and_zero_timeout_are_rejected() { |
| 825 | let config = HooksConfig { |
| 826 | enabled: true, |
| 827 | hooks: vec![ |
| 828 | Hook::new(HookEvent::SessionStart, " ").with_name("blank"), |
| 829 | Hook::new(HookEvent::SessionEnd, "true") |
| 830 | .with_name("instant") |
| 831 | .with_timeout(0), |
| 832 | ], |
| 833 | ..HooksConfig::default() |
| 834 | }; |
| 835 | let problems = config.validate(); |
| 836 | assert_eq!(problems.iter().filter(|p| p.rejected).count(), 2); |
| 837 | } |
| 838 | |
| 839 | #[test] |
| 840 | fn background_flag_truth_is_reported_per_event() { |
| 841 | // `shell_env` does not honor the flag at all — that is a warning, and |
| 842 | // the hook still runs. |
| 843 | let shell_env = HooksConfig { |
| 844 | enabled: true, |
| 845 | hooks: vec![ |
| 846 | Hook::new(HookEvent::ShellEnv, "true") |
| 847 | .with_name("creds") |
| 848 | .background(), |
| 849 | ], |
| 850 | ..HooksConfig::default() |
| 851 | }; |
| 852 | let problems = shell_env.validate(); |
| 853 | assert_eq!(problems.len(), 1); |
| 854 | assert!(!problems[0].rejected, "the hook still runs, in foreground"); |
| 855 | assert!(problems[0].detail.contains("not honored")); |
| 856 | assert!(!HookEvent::ShellEnv.honors_background()); |
| 857 | |
| 858 | // A background steering hook is honored scheduling, but it silently |
| 859 | // stops steering — worth saying out loud. |
| 860 | for event in [HookEvent::MessageSubmit, HookEvent::ToolCallBefore] { |
| 861 | let config = HooksConfig { |
| 862 | enabled: true, |
| 863 | hooks: vec![Hook::new(event, "true").with_name("gate").background()], |
| 864 | ..HooksConfig::default() |
| 865 | }; |
| 866 | let problems = config.validate(); |
| 867 | assert_eq!(problems.len(), 1, "{}", event.as_str()); |
| 868 | assert!(!problems[0].rejected); |
| 869 | assert!(problems[0].detail.contains("observer-only")); |
| 870 | assert!(event.honors_background()); |
| 871 | } |
| 872 | |
| 873 | // A background observer hook is unremarkable. |
| 874 | let observer = HooksConfig { |
| 875 | enabled: true, |
| 876 | hooks: vec![Hook::new(HookEvent::TurnEnd, "true").background()], |
| 877 | ..HooksConfig::default() |
| 878 | }; |
| 879 | assert!(observer.validate().is_empty()); |
| 880 | } |
| 881 | |
| 882 | #[test] |
| 883 | fn problem_summaries_carry_no_command_or_path() { |
| 884 | let problem = HookConfigProblem { |
| 885 | name: Some("gate".to_string()), |
| 886 | event: Some(HookEvent::ToolCallBefore), |
| 887 | detail: "example detail".to_string(), |
| 888 | rejected: true, |
| 889 | }; |
| 890 | let summary = problem_summary(&problem); |
| 891 | assert!(summary.contains("rejected")); |
| 892 | assert!(summary.contains("tool_call_before")); |
| 893 | assert!(summary.contains("gate")); |
| 894 | |
| 895 | let unnamed = HookConfigProblem { |
| 896 | name: None, |
| 897 | rejected: false, |
| 898 | ..problem |
| 899 | }; |
| 900 | assert!(problem_summary(&unnamed).contains("(unnamed)")); |
| 901 | assert!(problem_summary(&unnamed).contains("warning")); |
| 902 | } |
| 903 | |
| 904 | #[test] |
| 905 | fn project_hook_file_read_is_bounded_before_toml_parse() { |
| 906 | let dir = tempfile::tempdir().expect("tempdir"); |
| 907 | let path = dir.path().join("hooks.toml"); |
| 908 | std::fs::write(&path, "x".repeat(super::PROJECT_HOOKS_FILE_MAX_BYTES + 1)) |
| 909 | .expect("write oversized hook config"); |
| 910 | let error = super::read_project_hooks_file(&path) |
| 911 | .expect_err("oversized project hook config must be rejected"); |
| 912 | assert_eq!(error.kind(), std::io::ErrorKind::InvalidData); |
| 913 | assert!(error.to_string().contains("1 MiB")); |
| 914 | } |
| 915 | |
| 916 | /// The seeded project hooks file must be inert: creating it can never |
| 917 | /// change behaviour, only teach the schema. |
| 918 | #[test] |
| 919 | fn project_hooks_template_parses_and_configures_nothing() { |
| 920 | let parsed: HooksConfig = |
| 921 | toml::from_str(PROJECT_HOOKS_TEMPLATE).expect("the seeded template must be valid TOML"); |
| 922 | assert!( |
| 923 | parsed.hooks.is_empty(), |
| 924 | "a freshly created hooks file must define no hooks" |
| 925 | ); |
| 926 | assert!(parsed.problems.is_empty()); |
| 927 | assert!( |
| 928 | PROJECT_HOOKS_TEMPLATE.contains("/hooks events"), |
| 929 | "the template must point at the event list rather than restate it" |
| 930 | ); |
| 931 | } |
| 932 | } |
| 933 |