Publish harness and TUI open-source

initial sync from the monorepo
This commit is contained in:
grokkybara[bot] 2026-07-16 06:46:02 +01:00
commit c68e39f604
2734 changed files with 1437016 additions and 0 deletions

View file

@ -0,0 +1,27 @@
[package]
license = "Apache-2.0"
name = "xai-grok-hooks"
version = "0.1.0"
edition.workspace = true
description = "Runtime hook system for Grok — file-based discovery, command execution, and policy enforcement"
[dependencies]
fastrand = { workspace = true }
regex = { workspace = true }
reqwest = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
shellexpand = "3.1"
thiserror = { workspace = true }
tokio = { workspace = true, features = ["process", "rt", "macros", "time"] }
tracing = { workspace = true }
url = { workspace = true }
xai-grok-config = { workspace = true }
xai-grok-tools = { workspace = true }
[dev-dependencies]
tempfile = { workspace = true }
tokio = { workspace = true, features = ["full"] }
[lints]
workspace = true

View file

@ -0,0 +1,119 @@
# Hook Examples
Sample hooks for Grok. Copy to `~/.grok/hooks/` to enable globally, or to `<project>/.grok/hooks/` for project-scoped hooks (requires `/hooks-trust`).
## Available Examples
### 1. Safe Shell Guard (`safe-shell.json`)
**Type:** blocking (`PreToolUse`)
Denies obviously destructive shell commands before they execute:
- `rm -rf /`, `sudo rm -rf`, `mkfs`, `dd` to devices, fork bombs
**Install:**
```sh
mkdir -p ~/.grok/hooks/bin
cp examples/hooks/safe-shell.json ~/.grok/hooks/
cp examples/hooks/bin/safe-shell-guard.sh ~/.grok/hooks/bin/
chmod +x ~/.grok/hooks/bin/safe-shell-guard.sh
```
### 2. No Recursive Grep (`no-recursive-grep.json`)
**Type:** blocking (`PreToolUse`)
Denies recursive `grep` invocations in the shell before they execute:
- `grep -r`, `grep -R`, `grep --recursive`, `grep --dereference-recursive`,
`grep -d recurse`, clustered flags (`grep -rn`, `grep -nri`), and `rgrep`
Recursive grep walks an entire directory tree into memory and can OOM-kill the
agent process on large repos. The system prompt already steers the model away from
this, but a prompt is advisory — this hook makes it a hard, deterministic block.
Point the model at the dedicated search tool (ripgrep-backed) instead.
It is careful to avoid false positives: `ls -R | grep foo` (the `-R` belongs to
`ls`), `grep -e -r file` (`-r` is the pattern), and `grep -- -r file` are all
allowed.
**Install:**
```sh
mkdir -p ~/.grok/hooks/bin
cp examples/hooks/no-recursive-grep.json ~/.grok/hooks/
cp examples/hooks/bin/no-recursive-grep-guard.py ~/.grok/hooks/bin/
chmod +x ~/.grok/hooks/bin/no-recursive-grep-guard.py
```
(Requires `python3` on `PATH`.)
### 3. Session Audit Log (`session-log.json`)
**Type:** passive (`SessionStart` + `SessionEnd`)
Appends session metadata to `~/.grok/session-audit.log` — event, session ID, cwd, timestamp.
**Install:**
```sh
mkdir -p ~/.grok/hooks/bin
cp examples/hooks/session-log.json ~/.grok/hooks/
cp examples/hooks/bin/session-log.sh ~/.grok/hooks/bin/
chmod +x ~/.grok/hooks/bin/session-log.sh
```
### 4. Tool Activity Logger (`tool-logger.json`)
**Type:** passive (`PreToolUse` + `PostToolUse`)
Logs all tool calls to `~/.grok/tool-activity.log` — tool name, event type, effective tool name, backgrounded status.
**Install:**
```sh
mkdir -p ~/.grok/hooks/bin
cp examples/hooks/tool-logger.json ~/.grok/hooks/
cp examples/hooks/bin/tool-logger.sh ~/.grok/hooks/bin/
chmod +x ~/.grok/hooks/bin/tool-logger.sh
```
## Format
Hook files use the Claude-compatible JSON format:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "bin/check.sh", "timeout": 5 }
]
}
]
}
}
```
- **Event names:** `SessionStart`, `PreToolUse`, `PostToolUse`, `SessionEnd`
- **Matcher:** regex on tool name. Claude names like `Bash`, `Read`, `Edit` are auto-expanded to also match Grok names (`run_terminal_cmd`, `read_file`, `search_replace`)
- **Timeout:** in seconds (default: 5)
- **Command:** path to script (relative to hook file directory) or inline shell command
## Script Contract
Scripts receive the hook event envelope as JSON on **stdin** and should write a response to **stdout**:
**For blocking hooks (`PreToolUse`):**
```json
{"decision":"allow"}
```
or
```json
{"decision":"deny","reason":"Explanation for the user"}
```
**Exit codes:** `0` = allow, `2` = deny, other = fail-open.
**For passive hooks:** stdout is informational only. Exit `0` for success.
## Uninstall
Remove the JSON file from `~/.grok/hooks/`. The hook stops running on the next session.

View file

@ -0,0 +1,386 @@
#!/usr/bin/env python3
"""PreToolUse hook that blocks recursive ``grep``.
Recursive grep (``grep -r``/``-R``/``--recursive``/``-d recurse``/``rgrep`` ...)
walks an entire directory tree into memory and can OOM-kill the agent process on
large repos. The system prompt only *asks* the model to avoid it; this hook
turns that into a hard, deterministic block.
Protocol: read the PreToolUse envelope as JSON on stdin and signal the decision
to the runner:
recursive grep -> deny: exit 2 + a deny JSON on stdout (+ reason on stderr)
anything else -> allow: exit 0, nothing on stdout
Any unexpected condition falls through to "allow" (fail-open), matching the
runner's contract -- only an explicit deny blocks the tool call.
Detection is a pure function (``command_is_recursive``) with no I/O, so it is
trivially unit-testable -- run ``no-recursive-grep-guard.py --self-test``.
Parsing is a single quote-aware lexer (``lex``) shared by every stage:
* a quoted span is one operand and is never read as a flag
(``grep "rm -rf" log`` and ``grep "-r" file`` are not recursive);
* shell ``#`` line-comments are dropped;
* live command substitutions ``$(...)`` / backticks (unquoted or inside
double quotes -- single quotes suppress them) are recursed into;
* pipeline/compound operators (``| & ; ( ) { }`` + newlines) split segments,
so a recursive flag must belong to grep, not e.g. ``ls -R | grep``;
* ``sh``/``bash -c "<script>"`` inner scripts are recursed into;
* transparent wrappers (``sudo``/``env``/``xargs``/...) are peeled, looking
past their own flags/args for grep.
"""
from __future__ import annotations
import json
import re
import sys
from typing import NamedTuple
SHELLS = {"sh", "bash", "dash", "zsh", "ash", "ksh", "mksh"}
# Wrappers whose real command may sit behind their own flags/args.
WRAPPERS = {
"sudo",
"doas",
"command",
"env",
"time",
"nice",
"nohup",
"stdbuf",
"exec",
"xargs",
"setsid",
}
GREPS = {"grep", "egrep", "fgrep"}
# grep options whose value is the following token (skip it so it is not a flag).
ARG_OPTS = {"-e", "-f", "-m", "-A", "-B", "-C", "-D"}
# Operators that separate pipeline segments / compounds (brace groups included).
OPERATOR_CHARS = set("|&;(){}\n\r")
ASSIGNMENT = re.compile(r"[A-Za-z_]\w*=")
# A short-flag cluster containing r/R -- grep's only r/R short flags both recurse.
SHORT_RECURSIVE = re.compile(r"-[A-Za-z]*[rR]")
MAX_DEPTH = 5
DENY_REASON = (
"Blocked: recursive grep (grep -r/-R/--recursive/rgrep) can read an entire "
"directory tree into memory and OOM-kill the agent process on large repos. Use the "
"dedicated search tool instead, which streams ripgrep results safely."
)
class Tok(NamedTuple):
"""One lexed token."""
text: str # token text, with surrounding quotes removed
quoted: bool # any part came from inside quotes -> operand, never a flag
op: bool # True if this is a shell operator that separates segments
def _read_paren_subst(s: str, i: int) -> tuple[int, str]:
"""Read a ``$(...)`` body starting at the ``$`` (index ``i``). Parens are
matched quote-aware so a ``)`` inside a string does not close it early.
Returns ``(index_after_closing_paren, body)``."""
n = len(s)
i += 2 # skip "$("
start = i
depth = 1
quote = None
while i < n and depth > 0:
c = s[i]
if quote:
if c == quote:
quote = None
elif c in ("'", '"'):
quote = c
elif c == "(":
depth += 1
elif c == ")":
depth -= 1
if depth == 0:
break
i += 1
return i + 1, s[start:i]
def _read_backtick_subst(s: str, i: int) -> tuple[int, str]:
"""Read a backtick substitution body starting at the opening backtick."""
n = len(s)
i += 1
start = i
while i < n and s[i] != "`":
i += 1
return i + 1, s[start:i]
def lex(s: str) -> tuple[list[Tok], list[str]]:
"""Single quote-aware pass over a command string. Returns the list of tokens
plus the bodies of any *live* command substitutions (to be recursed into)."""
tokens: list[Tok] = []
subst: list[str] = []
buf: list[str] = []
quoted = False
quote = None
i, n = 0, len(s)
def flush() -> None:
nonlocal buf, quoted
if buf or quoted:
tokens.append(Tok("".join(buf), quoted, False))
buf, quoted = [], False
while i < n:
c = s[i]
if quote == "'": # single quotes: everything literal, no substitution
if c == "'":
quote = None
else:
buf.append(c)
i += 1
continue
if quote == '"': # double quotes: literal text, but substitutions live
if c == '"':
quote = None
i += 1
elif c == "$" and i + 1 < n and s[i + 1] == "(":
i, body = _read_paren_subst(s, i)
subst.append(body)
elif c == "`":
i, body = _read_backtick_subst(s, i)
subst.append(body)
else:
buf.append(c)
i += 1
continue
# unquoted
if c in ("'", '"'):
quote = c
quoted = True
i += 1
elif c == "#" and not buf and not quoted:
break # comment to end of line
elif c == "$" and i + 1 < n and s[i + 1] == "(":
i, body = _read_paren_subst(s, i)
subst.append(body)
elif c == "`":
i, body = _read_backtick_subst(s, i)
subst.append(body)
elif c in " \t":
flush()
i += 1
elif c in OPERATOR_CHARS:
flush()
tokens.append(Tok(c, False, True))
i += 1
else:
buf.append(c)
i += 1
flush()
return tokens, subst
def _split_segments(tokens: list[Tok]) -> list[list[Tok]]:
"""Cut a token list into pipeline segments on operator tokens."""
segments: list[list[Tok]] = []
current: list[Tok] = []
for tok in tokens:
if tok.op:
if current:
segments.append(current)
current = []
else:
current.append(tok)
if current:
segments.append(current)
return segments
def _basename(text: str) -> str:
return text.rsplit("/", 1)[-1]
def _grep_args_recursive(args: list[Tok]) -> bool:
"""True if grep's argument list requests recursion."""
skip_arg = False # previous option consumes this token as its value
dir_arg = False # that consumed value belongs to -d / --directories
for arg in args:
if skip_arg:
if dir_arg and arg.text == "recurse":
return True
skip_arg = dir_arg = False
continue
if arg.quoted:
continue # a quoted operand is literal text, never a flag
t = arg.text
if t == "--":
return False # end of options; nothing after it is a flag
if t in ("-d", "--directories"):
skip_arg = dir_arg = True
elif t.startswith("--directories="):
if t.endswith("=recurse"):
return True
elif t in ARG_OPTS:
skip_arg = True
elif t in ("--recursive", "--dereference-recursive") or SHORT_RECURSIVE.match(t):
return True
return False
def _shell_script_recursive(args: list[Tok], depth: int) -> bool:
"""Re-inspect a shell interpreter's ``-c`` script (and trailing words)."""
i = 0
while i < len(args) and not args[i].quoted and args[i].text.startswith("-"):
i += 1 # skip the leading run of shell flags (-c, -lc, ...)
script = " ".join(a.text for a in args[i:])
return bool(script) and command_is_recursive(script, depth + 1)
def _segment_recursive(words: list[Tok], depth: int) -> bool:
"""True if one pipeline segment runs grep recursively."""
idx = 0
n = len(words)
while idx < n and not words[idx].quoted and ASSIGNMENT.match(words[idx].text):
idx += 1 # skip leading VAR=value assignments
if idx >= n:
return False
base = _basename(words[idx].text)
# Peel transparent wrappers: the real command may sit behind the wrapper's
# own flags/args, so seek the next grep/shell among the following words.
while base in WRAPPERS:
idx += 1
while idx < n:
b = _basename(words[idx].text)
if b == "rgrep" or b in GREPS or b in SHELLS:
break
idx += 1
if idx >= n:
return False
base = _basename(words[idx].text)
if base == "rgrep":
return True
if base in SHELLS:
return _shell_script_recursive(words[idx + 1 :], depth)
if base in GREPS:
return _grep_args_recursive(words[idx + 1 :])
return False
def command_is_recursive(cmd: str, depth: int = 0) -> bool:
"""Pure predicate: True if the shell command runs grep recursively."""
if depth >= MAX_DEPTH:
return False
tokens, substitutions = lex(cmd)
for body in substitutions:
if command_is_recursive(body, depth + 1):
return True
return any(_segment_recursive(seg, depth) for seg in _split_segments(tokens))
def extract_command(envelope: object) -> str | None:
"""Pull toolInput.command out of the PreToolUse envelope, or None."""
if not isinstance(envelope, dict):
return None
# Accept both the camelCase (toolInput) and snake_case (tool_input) shapes.
tool_input = envelope.get("toolInput") or envelope.get("tool_input")
if not isinstance(tool_input, dict):
return None
command = tool_input.get("command")
return command if isinstance(command, str) and command else None
# Allow/deny cases exercised by --self-test; keep in sync with the README.
SELF_TEST_CASES: list[tuple[str, bool]] = [
# --- recursive (deny) ---
("grep -r foo .", True),
("grep -R foo .", True),
("grep --recursive foo .", True),
("grep -rn TODO src", True),
("rgrep foo .", True),
("/usr/bin/grep -r x", True),
("egrep -r x .", True),
("FOO=bar grep -r x", True),
("cat x | grep -r y", True),
("sudo grep -r x", True),
("sudo -u root grep -r x", True),
("xargs -0 grep -r .", True),
("nice -n 10 grep -r x", True),
("grep -d recurse x", True),
('grep -d "recurse" x', True),
("grep --directories=recurse x", True),
('grep --include="*.rs" -r .', True),
('grep -e "p" -r .', True),
('bash -c "grep -r x"', True),
("bash -c grep -r x", True),
('echo "$(grep -r x)"', True),
("foo=$(grep -r x)", True),
("cat <(grep -r x)", True),
("{ grep -r x; }", True),
("grep -r x . # note", True),
# --- not recursive (allow) ---
("grep foo file", False),
("grep -n foo file", False),
("ls -R | grep foo", False),
("grep -e -r file", False),
("grep -- -r file", False),
("grep -A 3 foo file", False),
("grep -d skip foo file", False),
('grep "rm -rf" log', False),
('grep "-r" file', False),
('grep --include="*.rs" foo file', False),
("grep foo file # uses -r", False),
("echo '$(grep -r x)'", False),
('echo "$(ls)"', False),
("sudo ls -R", False),
("echo grep -r as text", False),
("xargs grep foo", False),
("{ echo hi; }", False),
("", False),
]
def self_test() -> int:
failures = 0
for cmd, want in SELF_TEST_CASES:
got = command_is_recursive(cmd)
if got != want:
failures += 1
print(f"FAIL: {cmd!r} -> {got} (want {want})")
total = len(SELF_TEST_CASES)
print(f"{total - failures}/{total} passed")
return 1 if failures else 0
def main() -> None:
if "--self-test" in sys.argv[1:]:
sys.exit(self_test())
try:
envelope = json.load(sys.stdin)
except (ValueError, OSError):
sys.exit(0) # unparseable input -> fail open (allow)
command = extract_command(envelope)
if command is None or not command_is_recursive(command):
sys.exit(0) # nothing to block -> silent allow
# Deny. Emit the grok-native decision (read by this repo's runner) and the
# Claude-style hookSpecificOutput for forward-compatibility, put the reason
# on stderr for runners that surface it there, and exit 2 so any exit-code
# based runner blocks too.
print(
json.dumps(
{
"decision": "deny",
"reason": DENY_REASON,
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": DENY_REASON,
},
}
)
)
print(DENY_REASON, file=sys.stderr)
sys.exit(2)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,52 @@
#!/bin/sh
# safe-shell-guard.sh — block obviously destructive shell commands
#
# This hook reads the PreToolUse envelope from stdin, extracts the
# command field from toolInput, and checks it against a blocklist.
#
# Returns {"decision":"deny","reason":"..."} + exit 2 for matches,
# {"decision":"allow"} + exit 0 otherwise.
INPUT=$(cat)
# Extract the command from the toolInput JSON.
# Uses basic grep/sed since jq may not be available everywhere.
COMMAND=$(echo "$INPUT" | grep -o '"command":"[^"]*"' | head -1 | sed 's/"command":"//;s/"$//')
if [ -z "$COMMAND" ]; then
echo '{"decision":"allow"}'
exit 0
fi
# Blocklist patterns (case-insensitive check).
LOWER_CMD=$(echo "$COMMAND" | tr '[:upper:]' '[:lower:]')
case "$LOWER_CMD" in
*"rm -rf /"*|*"rm -rf --no-preserve-root"*)
echo '{"decision":"deny","reason":"Blocked: rm -rf / is not allowed"}'
exit 2
;;
*"sudo rm -rf"*)
echo '{"decision":"deny","reason":"Blocked: sudo rm -rf is not allowed"}'
exit 2
;;
*"mkfs"*)
echo '{"decision":"deny","reason":"Blocked: mkfs commands are not allowed"}'
exit 2
;;
*"dd if=/dev/zero of=/dev"*|*"dd if=/dev/urandom of=/dev"*)
echo '{"decision":"deny","reason":"Blocked: dd to device is not allowed"}'
exit 2
;;
*":(){"|*"fork bomb"*)
echo '{"decision":"deny","reason":"Blocked: fork bomb detected"}'
exit 2
;;
*"> /dev/sda"*|*"> /dev/hda"*|*"> /dev/nvme"*)
echo '{"decision":"deny","reason":"Blocked: direct write to block device"}'
exit 2
;;
esac
echo '{"decision":"allow"}'
exit 0

View file

@ -0,0 +1,18 @@
#!/bin/sh
# session-log.sh — append session events to an audit log
#
# Reads the hook envelope from stdin and appends a one-line JSON entry
# to ~/.grok/session-audit.log with event name, session ID, cwd, and
# timestamp.
INPUT=$(cat)
EVENT=$(echo "$INPUT" | grep -o '"hookEventName":"[^"]*"' | sed 's/"hookEventName":"//;s/"$//')
SESSION=$(echo "$INPUT" | grep -o '"sessionId":"[^"]*"' | sed 's/"sessionId":"//;s/"$//')
CWD=$(echo "$INPUT" | grep -o '"cwd":"[^"]*"' | sed 's/"cwd":"//;s/"$//')
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
LOG_FILE="${HOME}/.grok/session-audit.log"
mkdir -p "$(dirname "$LOG_FILE")"
echo "{\"timestamp\":\"${TIMESTAMP}\",\"event\":\"${EVENT}\",\"session\":\"${SESSION}\",\"cwd\":\"${CWD}\"}" >> "$LOG_FILE"

View file

@ -0,0 +1,18 @@
#!/bin/sh
# tool-logger.sh — log tool calls to a local activity file
#
# Reads the hook envelope from stdin and appends a one-line JSON entry
# to ~/.grok/tool-activity.log with event name, tool name, and timestamp.
# `toolName` is the resolved tool (e.g. `linear__save_issue` for MCP calls).
INPUT=$(cat)
EVENT=$(echo "$INPUT" | grep -o '"hookEventName":"[^"]*"' | sed 's/"hookEventName":"//;s/"$//')
TOOL=$(echo "$INPUT" | grep -o '"toolName":"[^"]*"' | head -1 | sed 's/"toolName":"//;s/"$//')
BACKGROUNDED=$(echo "$INPUT" | grep -o '"isBackgrounded":[a-z]*' | sed 's/"isBackgrounded"://')
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
LOG_FILE="${HOME}/.grok/tool-activity.log"
mkdir -p "$(dirname "$LOG_FILE")"
echo "{\"timestamp\":\"${TIMESTAMP}\",\"event\":\"${EVENT}\",\"tool\":\"${TOOL}\",\"backgrounded\":${BACKGROUNDED:-false}}" >> "$LOG_FILE"

View file

@ -0,0 +1,16 @@
{
"hooks": {
"PreToolUse": [
{
"matcher": "^(Bash|bash|run_terminal_command|run_terminal_cmd|Shell)$",
"hooks": [
{
"type": "command",
"command": "bin/no-recursive-grep-guard.py",
"timeout": 5
}
]
}
]
}
}

View file

@ -0,0 +1,16 @@
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "bin/safe-shell-guard.sh",
"timeout": 5
}
]
}
]
}
}

View file

@ -0,0 +1,18 @@
{
"hooks": {
"SessionStart": [
{
"hooks": [
{ "type": "command", "command": "bin/session-log.sh", "timeout": 5 }
]
}
],
"SessionEnd": [
{
"hooks": [
{ "type": "command", "command": "bin/session-log.sh", "timeout": 5 }
]
}
]
}
}

View file

@ -0,0 +1,18 @@
{
"hooks": {
"PreToolUse": [
{
"hooks": [
{ "type": "command", "command": "bin/tool-logger.sh", "timeout": 5 }
]
}
],
"PostToolUse": [
{
"hooks": [
{ "type": "command", "command": "bin/tool-logger.sh", "timeout": 5 }
]
}
]
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,892 @@
use std::collections::HashMap;
use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::config::{self, HookSpec};
use crate::error::HookError;
use crate::event::HookEventName;
use crate::matcher::HookMatcher;
/// The loaded set of hooks, indexed by event type for fast lookup.
///
/// This is a point-in-time snapshot. Edits to hook files on disk are only
/// picked up by new sessions.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HookRegistry {
hooks: HashMap<HookEventName, Vec<HookSpec>>,
}
impl HookRegistry {
/// Returns the hooks registered for the given event type.
pub fn hooks_for(&self, event: HookEventName) -> &[HookSpec] {
self.hooks.get(&event).map(|v| v.as_slice()).unwrap_or(&[])
}
/// Returns true if the registry contains no hooks at all.
pub fn is_empty(&self) -> bool {
self.hooks.values().all(|v| v.is_empty())
}
/// Returns the total number of hooks across all event types.
pub fn len(&self) -> usize {
self.hooks.values().map(|v| v.len()).sum()
}
/// Append additional hook specs into this registry.
pub fn append_specs(&mut self, specs: Vec<HookSpec>) {
for spec in specs {
self.hooks.entry(spec.event).or_default().push(spec);
}
}
/// Remove all hook specs whose name starts with the given prefix.
pub fn remove_by_prefix(&mut self, prefix: &str) {
for specs in self.hooks.values_mut() {
specs.retain(|s| !s.name.starts_with(prefix));
}
}
/// All event types in canonical display order.
const ALL_EVENTS: &[HookEventName] = &[
HookEventName::SessionStart,
HookEventName::UserPromptSubmit,
HookEventName::PreToolUse,
HookEventName::PostToolUse,
HookEventName::PostToolUseFailure,
HookEventName::PermissionDenied,
HookEventName::Stop,
HookEventName::StopFailure,
HookEventName::Notification,
HookEventName::SubagentStart,
HookEventName::SubagentStop,
HookEventName::SubagentEnd,
HookEventName::PreCompact,
HookEventName::PostCompact,
HookEventName::SessionEnd,
];
/// Returns all hooks as a flat list, ordered by event type then position.
pub fn all_hooks(&self) -> Vec<&HookSpec> {
let mut all = Vec::new();
for event in Self::ALL_EVENTS {
all.extend(self.hooks_for(*event));
}
all
}
/// Recompile the `matcher` field on every [`HookSpec`] from its
/// `configured_matcher` pattern string.
///
/// After deserialization, the compiled [`HookMatcher`] is `None`
/// (it is `#[serde(skip)]`). This method rebuilds it using the
/// same logic as the original parse path, via [`HookMatcher::new`].
///
/// Specs whose `configured_matcher` is `None` (match-all) are
/// left untouched. Invalid patterns are logged and the spec's
/// matcher remains `None` (match-all fallback), which is the
/// safest fail-open behavior.
pub fn recompile_matchers(&mut self) {
for specs in self.hooks.values_mut() {
for spec in specs.iter_mut() {
if let Some(ref pattern) = spec.configured_matcher {
match HookMatcher::new(pattern) {
Ok(m) => spec.matcher = Some(m),
Err(e) => {
tracing::warn!(
hook = %spec.name,
pattern = %pattern,
error = %e,
"hooks: failed to recompile matcher after deserialization"
);
// Leave matcher as None → match-all (fail-open).
}
}
}
}
}
}
}
/// A hook source: either a single settings file or a directory of hook files.
#[derive(Debug, Clone)]
pub enum HookSource<'a> {
/// A single JSON settings file (e.g. `~/.claude/settings.json`).
/// The `hooks` key is extracted; other keys are ignored.
SettingsFile(&'a Path),
/// A directory of `*.json` hook files (e.g. `~/.grok/hooks/`).
Directory(&'a Path),
}
/// Load hooks from global and project sources.
///
/// Sources are additive: hooks from all sources are merged into a single
/// registry. Global hooks run before project hooks. Within each scope,
/// earlier sources execute before later sources.
///
/// Returns the registry plus any non-fatal load errors.
/// A fully empty registry is valid (no-op when no hooks are configured).
pub fn load_hooks_from_sources(
global_sources: &[HookSource<'_>],
project_sources: &[HookSource<'_>],
) -> (HookRegistry, Vec<HookError>) {
tracing::debug!(
global_sources = global_sources.len(),
project_sources = project_sources.len(),
"hooks: starting discovery"
);
let mut all_specs = Vec::new();
let mut all_errors = Vec::new();
// Load global hooks first (precedence order: global, then project).
for source in global_sources {
let (mut specs, errors) = load_from_source(source);
for spec in &mut specs {
spec.name = format!("global/{}", spec.name);
}
tracing::debug!(
source = ?source,
count = specs.len(),
"hooks: loaded from global source"
);
all_specs.extend(specs);
all_errors.extend(errors);
}
// Load project hooks second.
for source in project_sources {
let (mut specs, errors) = load_from_source(source);
for spec in &mut specs {
spec.name = format!("project/{}", spec.name);
}
tracing::debug!(
source = ?source,
count = specs.len(),
"hooks: loaded from project source"
);
all_specs.extend(specs);
all_errors.extend(errors);
}
// Index by event type, deduplicating by hook content (command/url) +
// matcher across all sources. This prevents the same hook from executing
// multiple times when it's defined in multiple sources (e.g., ~/.grok/hooks/ +
// ~/.claude/settings.json + ~/.cursor/hooks.json), while still allowing
// hooks that share a command/URL but have different matchers (e.g. tool-scoped
// hooks) to all run.
//
// Deduplication key: (event, command_raw, url_raw, configured_matcher).
// Hooks with identical content + matcher are deduplicated regardless of
// source. Global hooks take precedence because they're loaded first.
let mut hooks: HashMap<HookEventName, Vec<HookSpec>> = HashMap::new();
let mut seen_content: std::collections::HashSet<(HookEventName, String, String, String)> =
std::collections::HashSet::new();
for spec in all_specs {
let key = (
spec.event,
spec.command_raw.clone().unwrap_or_default(),
spec.url_raw.clone().unwrap_or_default(),
spec.configured_matcher.clone().unwrap_or_default(),
);
if seen_content.insert(key) {
hooks.entry(spec.event).or_default().push(spec);
} else {
tracing::debug!(
hook_name = %spec.name,
event = %spec.event,
matcher = ?spec.configured_matcher,
"hooks: skipping duplicate hook (same content + matcher already loaded from earlier source)"
);
}
}
let registry = HookRegistry { hooks };
tracing::info!(
total_hooks = registry.len(),
session_start = registry.hooks_for(HookEventName::SessionStart).len(),
pre_tool = registry.hooks_for(HookEventName::PreToolUse).len(),
post_tool = registry.hooks_for(HookEventName::PostToolUse).len(),
session_end = registry.hooks_for(HookEventName::SessionEnd).len(),
stop = registry.hooks_for(HookEventName::Stop).len(),
notification = registry.hooks_for(HookEventName::Notification).len(),
user_prompt_submit = registry.hooks_for(HookEventName::UserPromptSubmit).len(),
subagent_start = registry.hooks_for(HookEventName::SubagentStart).len(),
subagent_stop = registry.hooks_for(HookEventName::SubagentStop).len()
+ registry.hooks_for(HookEventName::SubagentEnd).len(),
"hooks: discovery complete"
);
(registry, all_errors)
}
/// Convenience wrapper: load hooks from a single global directory and optional
/// project directory. Used by the existing shell integration.
pub fn load_hooks(
global_dir: Option<&Path>,
project_dir: Option<&Path>,
) -> (HookRegistry, Vec<HookError>) {
let global: Vec<HookSource<'_>> = global_dir.into_iter().map(HookSource::Directory).collect();
let project: Vec<HookSource<'_>> = project_dir.into_iter().map(HookSource::Directory).collect();
load_hooks_from_sources(&global, &project)
}
/// Load hooks from a single source (settings file or directory).
fn load_from_source(source: &HookSource<'_>) -> (Vec<HookSpec>, Vec<HookError>) {
match source {
HookSource::SettingsFile(path) => load_hooks_from_settings_file(path),
HookSource::Directory(dir) => load_hooks_from_directory(dir),
}
}
/// Load hooks from a single JSON settings file.
///
/// Reads the file, extracts the `hooks` key, and parses it. If the file
/// does not exist or has no `hooks` key, returns empty results (not an error).
fn load_hooks_from_settings_file(path: &Path) -> (Vec<HookSpec>, Vec<HookError>) {
let content = match std::fs::read_to_string(path) {
Ok(c) => c,
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
return (Vec::new(), Vec::new()); // Missing file is fine.
}
return (
Vec::new(),
vec![HookError::ReadFile {
path: path.to_path_buf(),
source: e,
}],
);
}
};
let (specs, errors) = config::parse_hook_file(&content, path);
for err in &errors {
tracing::warn!("hook loading from settings file: {err}");
}
(specs, errors)
}
/// Load hooks from a single directory.
///
/// - Only loads `*.json` files.
/// - Ignores hidden/temp/editor files (dotfiles, `~`-suffixed, `.swp`).
/// - Sorts files lexicographically for deterministic ordering.
fn load_hooks_from_directory(dir: &Path) -> (Vec<HookSpec>, Vec<HookError>) {
let mut specs = Vec::new();
let mut errors = Vec::new();
let entries = match std::fs::read_dir(dir) {
Ok(e) => e,
Err(e) => {
// Missing directory is not an error — it just means no hooks.
if e.kind() == std::io::ErrorKind::NotFound {
return (specs, errors);
}
errors.push(HookError::ReadFile {
path: dir.to_path_buf(),
source: e,
});
return (specs, errors);
}
};
// Collect and sort file paths lexicographically.
let mut json_files: Vec<std::path::PathBuf> = Vec::new();
for entry in entries {
let entry = match entry {
Ok(e) => e,
Err(e) => {
errors.push(HookError::ReadFile {
path: dir.to_path_buf(),
source: e,
});
continue;
}
};
let path = entry.path();
if !is_valid_hook_file(&path) {
continue;
}
json_files.push(path);
}
json_files.sort();
// Parse each file.
for path in json_files {
let content = match std::fs::read_to_string(&path) {
Ok(c) => c,
Err(e) => {
errors.push(HookError::ReadFile {
path: path.clone(),
source: e,
});
continue;
}
};
let (file_specs, file_errors) = config::parse_hook_file(&content, &path);
for err in &file_errors {
tracing::warn!("hook loading: {err}");
}
specs.extend(file_specs);
errors.extend(file_errors);
}
(specs, errors)
}
/// Check whether a path is a valid hook file (*.json, not hidden/temp).
fn is_valid_hook_file(path: &Path) -> bool {
let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
return false;
};
// Must have .json extension.
if path.extension().and_then(|e| e.to_str()) != Some("json") {
return false;
}
// Skip hidden files (dotfiles).
if name.starts_with('.') {
return false;
}
// Skip editor temp files.
if name.ends_with('~') || name.ends_with(".swp") || name.ends_with(".swo") {
return false;
}
// Must be a file, not a directory.
path.is_file()
}
#[cfg(test)]
mod tests {
use super::*;
fn write_json(dir: &Path, name: &str, content: &str) {
std::fs::write(dir.join(name), content).unwrap();
}
/// Create a simple compatible-format JSON hook file for the given event.
/// The `unique_id` parameter ensures each hook has a unique command,
/// preventing deduplication when testing multiple files.
fn simple_hook(event: &str) -> String {
simple_hook_with_id(event, "test")
}
/// Create a simple compatible-format JSON hook file with a unique command.
fn simple_hook_with_id(event: &str, id: &str) -> String {
serde_json::json!({
"hooks": {
event: [{"hooks": [{"type": "command", "command": format!("{}.sh", id)}]}]
}
})
.to_string()
}
#[test]
fn load_empty_dirs() {
let dir = tempfile::tempdir().unwrap();
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty());
assert!(registry.is_empty());
assert_eq!(registry.len(), 0);
}
#[test]
fn load_missing_dirs() {
let (registry, errors) = load_hooks(None, None);
assert!(errors.is_empty());
assert!(registry.is_empty());
}
#[test]
fn load_nonexistent_dir() {
let (registry, errors) = load_hooks(Some(Path::new("/nonexistent/path/hooks")), None);
assert!(errors.is_empty()); // NotFound is silent
assert!(registry.is_empty());
}
#[test]
fn load_single_hook() {
let dir = tempfile::tempdir().unwrap();
write_json(dir.path(), "safety.json", &simple_hook("PreToolUse"));
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty(), "errors: {errors:?}");
assert_eq!(registry.len(), 1);
let hooks = registry.hooks_for(HookEventName::PreToolUse);
assert_eq!(hooks.len(), 1);
}
#[test]
fn lexicographic_ordering_across_files() {
let dir = tempfile::tempdir().unwrap();
// Use unique IDs so hooks aren't deduplicated.
write_json(
dir.path(),
"02-second.json",
&simple_hook_with_id("PreToolUse", "second"),
);
write_json(
dir.path(),
"01-first.json",
&simple_hook_with_id("PreToolUse", "first"),
);
write_json(
dir.path(),
"03-third.json",
&simple_hook_with_id("PreToolUse", "third"),
);
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty());
let hooks = registry.hooks_for(HookEventName::PreToolUse);
assert_eq!(hooks.len(), 3);
// All hooks are PreToolUse, loaded in file order (01, 02, 03).
}
#[test]
fn global_before_project() {
let global = tempfile::tempdir().unwrap();
let project = tempfile::tempdir().unwrap();
// Use unique IDs so hooks aren't deduplicated.
write_json(
global.path(),
"global.json",
&simple_hook_with_id("PreToolUse", "global"),
);
write_json(
project.path(),
"project.json",
&simple_hook_with_id("PreToolUse", "project"),
);
let (registry, errors) = load_hooks(Some(global.path()), Some(project.path()));
assert!(errors.is_empty());
let hooks = registry.hooks_for(HookEventName::PreToolUse);
assert_eq!(hooks.len(), 2);
}
#[test]
fn skip_hidden_and_non_json_files() {
let dir = tempfile::tempdir().unwrap();
write_json(dir.path(), "valid.json", &simple_hook("SessionStart"));
write_json(dir.path(), ".hidden.json", &simple_hook("SessionStart"));
write_json(dir.path(), "backup.json~", "{}");
write_json(dir.path(), "not-json.txt", "{}");
write_json(dir.path(), "not-json.toml", "version = 1");
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty());
assert_eq!(registry.len(), 1);
}
#[test]
fn multiple_handlers_in_one_file() {
let dir = tempfile::tempdir().unwrap();
let content = r#"{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "a.sh" },
{ "type": "command", "command": "b.sh" }
]
}
]
}
}"#;
write_json(dir.path(), "multi.json", content);
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty());
let hooks = registry.hooks_for(HookEventName::PreToolUse);
assert_eq!(hooks.len(), 2);
}
#[test]
fn invalid_file_skipped_others_loaded() {
let dir = tempfile::tempdir().unwrap();
write_json(dir.path(), "01-good.json", &simple_hook("SessionStart"));
write_json(dir.path(), "02-bad.json", "not valid json {{{");
write_json(dir.path(), "03-also-good.json", &simple_hook("SessionEnd"));
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert_eq!(errors.len(), 1);
assert!(matches!(&errors[0], HookError::ParseFile { .. }));
assert_eq!(registry.len(), 2);
}
#[test]
fn hooks_indexed_by_event_type() {
let dir = tempfile::tempdir().unwrap();
// One file with all four event types.
let content = r#"{
"hooks": {
"SessionStart": [{"hooks": [{"type": "command", "command": "a.sh"}]}],
"PreToolUse": [{"hooks": [{"type": "command", "command": "b.sh"}]}],
"PostToolUse": [{"hooks": [{"type": "command", "command": "c.sh"}]}],
"SessionEnd": [{"hooks": [{"type": "command", "command": "d.sh"}]}]
}
}"#;
write_json(dir.path(), "all.json", content);
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty());
assert_eq!(registry.hooks_for(HookEventName::SessionStart).len(), 1);
assert_eq!(registry.hooks_for(HookEventName::PreToolUse).len(), 1);
assert_eq!(registry.hooks_for(HookEventName::PostToolUse).len(), 1);
assert_eq!(registry.hooks_for(HookEventName::SessionEnd).len(), 1);
}
#[test]
fn all_hooks_covers_every_event_type() {
let dir = tempfile::tempdir().unwrap();
// Create hooks for all 10 event types in one file.
let content = r#"{
"hooks": {
"SessionStart": [{"hooks": [{"type": "command", "command": "a.sh"}]}],
"PreToolUse": [{"hooks": [{"type": "command", "command": "b.sh"}]}],
"PostToolUse": [{"hooks": [{"type": "command", "command": "c.sh"}]}],
"SessionEnd": [{"hooks": [{"type": "command", "command": "d.sh"}]}],
"Stop": [{"hooks": [{"type": "command", "command": "e.sh"}]}],
"Notification": [{"hooks": [{"type": "command", "command": "f.sh"}]}],
"UserPromptSubmit": [{"hooks": [{"type": "command", "command": "g.sh"}]}],
"SubagentStart": [{"hooks": [{"type": "command", "command": "h.sh"}]}],
"SubagentStop": [{"hooks": [{"type": "command", "command": "i.sh"}]}],
"SubagentEnd": [{"hooks": [{"type": "command", "command": "j.sh"}]}]
}
}"#;
write_json(dir.path(), "all-events.json", content);
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty(), "errors: {errors:?}");
assert_eq!(registry.len(), 10);
// all_hooks() must return all 10 — not just the original 4.
let all = registry.all_hooks();
assert_eq!(
all.len(),
10,
"all_hooks() returned {} hooks, expected 10 (all event types)",
all.len()
);
// Verify each event type is represented.
let events: Vec<HookEventName> = all.iter().map(|h| h.event).collect();
assert!(events.contains(&HookEventName::SessionStart));
assert!(events.contains(&HookEventName::PreToolUse));
assert!(events.contains(&HookEventName::PostToolUse));
assert!(events.contains(&HookEventName::SessionEnd));
assert!(events.contains(&HookEventName::Stop));
assert!(events.contains(&HookEventName::Notification));
assert!(events.contains(&HookEventName::UserPromptSubmit));
assert!(events.contains(&HookEventName::SubagentStart));
assert!(events.contains(&HookEventName::SubagentStop));
assert!(events.contains(&HookEventName::SubagentEnd));
}
#[test]
fn is_valid_hook_file_cases() {
let dir = tempfile::tempdir().unwrap();
let valid = dir.path().join("hooks.json");
std::fs::write(&valid, "").unwrap();
assert!(is_valid_hook_file(&valid));
let hidden = dir.path().join(".hidden.json");
std::fs::write(&hidden, "").unwrap();
assert!(!is_valid_hook_file(&hidden));
let backup = dir.path().join("backup.json~");
std::fs::write(&backup, "").unwrap();
assert!(!is_valid_hook_file(&backup));
let txt = dir.path().join("readme.txt");
std::fs::write(&txt, "").unwrap();
assert!(!is_valid_hook_file(&txt));
let toml = dir.path().join("hooks.toml");
std::fs::write(&toml, "").unwrap();
assert!(!is_valid_hook_file(&toml)); // TOML no longer accepted
}
// ── Settings file discovery tests ────────────────────────────
#[test]
fn load_from_settings_file() {
let dir = tempfile::tempdir().unwrap();
let settings = dir.path().join("settings.json");
std::fs::write(
&settings,
r#"{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"check.sh"}]}]}}"#,
)
.unwrap();
let (registry, errors) =
load_hooks_from_sources(&[HookSource::SettingsFile(&settings)], &[]);
assert!(errors.is_empty(), "errors: {errors:?}");
assert_eq!(registry.len(), 1);
}
#[test]
fn load_from_missing_settings_file() {
let (registry, errors) = load_hooks_from_sources(
&[HookSource::SettingsFile(Path::new(
"/nonexistent/settings.json",
))],
&[],
);
assert!(errors.is_empty()); // Missing file is fine, not an error.
assert!(registry.is_empty());
}
#[test]
fn load_from_settings_file_no_hooks_key() {
let dir = tempfile::tempdir().unwrap();
let settings = dir.path().join("settings.json");
std::fs::write(&settings, r#"{"theme": "dark", "model": "grok-3"}"#).unwrap();
let (registry, errors) =
load_hooks_from_sources(&[HookSource::SettingsFile(&settings)], &[]);
assert!(errors.is_empty());
assert!(registry.is_empty());
}
#[test]
fn mixed_sources_settings_and_directory() {
let dir = tempfile::tempdir().unwrap();
// Settings file with one hook.
let settings = dir.path().join("settings.json");
std::fs::write(
&settings,
r#"{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"from-settings.sh"}]}]}}"#,
)
.unwrap();
// Directory with another hook.
let hooks_dir = dir.path().join("hooks");
std::fs::create_dir_all(&hooks_dir).unwrap();
write_json(&hooks_dir, "extra.json", &simple_hook("SessionStart"));
let (registry, errors) = load_hooks_from_sources(
&[
HookSource::SettingsFile(&settings),
HookSource::Directory(&hooks_dir),
],
&[],
);
assert!(errors.is_empty(), "errors: {errors:?}");
// Both hooks should be loaded (additive merge).
assert_eq!(registry.len(), 2);
assert_eq!(registry.hooks_for(HookEventName::PreToolUse).len(), 1);
assert_eq!(registry.hooks_for(HookEventName::SessionStart).len(), 1);
}
#[test]
fn global_and_project_settings_merged() {
let dir = tempfile::tempdir().unwrap();
let global_settings = dir.path().join("global.json");
std::fs::write(
&global_settings,
r#"{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"global.sh"}]}]}}"#,
)
.unwrap();
let project_settings = dir.path().join("project.json");
std::fs::write(
&project_settings,
r#"{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"project.sh"}]}]}}"#,
)
.unwrap();
let (registry, errors) = load_hooks_from_sources(
&[HookSource::SettingsFile(&global_settings)],
&[HookSource::SettingsFile(&project_settings)],
);
assert!(errors.is_empty());
let hooks = registry.hooks_for(HookEventName::PreToolUse);
assert_eq!(hooks.len(), 2);
// Global hook first, project hook second.
assert!(hooks[0].name.starts_with("global/"));
assert!(hooks[1].name.starts_with("project/"));
}
#[test]
fn deduplicates_hooks_with_same_content_across_sources() {
let dir = tempfile::tempdir().unwrap();
// Create three sources with the SAME hook command.
// Only the first one (global) should be kept.
let global_settings = dir.path().join("global.json");
std::fs::write(
&global_settings,
r#"{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"safety.sh"}]}]}}"#,
)
.unwrap();
let claude_settings = dir.path().join("claude.json");
std::fs::write(
&claude_settings,
r#"{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"safety.sh"}]}]}}"#,
)
.unwrap();
let cursor_settings = dir.path().join("cursor.json");
std::fs::write(
&cursor_settings,
r#"{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"safety.sh"}]}]}}"#,
)
.unwrap();
let (registry, errors) = load_hooks_from_sources(
&[
HookSource::SettingsFile(&global_settings),
HookSource::SettingsFile(&claude_settings),
HookSource::SettingsFile(&cursor_settings),
],
&[],
);
assert!(errors.is_empty());
// Only one hook should be loaded (the first one, from global).
let hooks = registry.hooks_for(HookEventName::SessionStart);
assert_eq!(
hooks.len(),
1,
"expected exactly 1 SessionStart hook after dedup, got {}",
hooks.len()
);
assert!(
hooks[0].name.starts_with("global/"),
"first source (global) should win, got: {}",
hooks[0].name
);
}
#[test]
fn different_commands_not_deduplicated() {
let dir = tempfile::tempdir().unwrap();
// Different hook commands - should NOT be deduplicated.
let global_settings = dir.path().join("global.json");
std::fs::write(
&global_settings,
r#"{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"first.sh"}]}]}}"#,
)
.unwrap();
let claude_settings = dir.path().join("claude.json");
std::fs::write(
&claude_settings,
r#"{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"second.sh"}]}]}}"#,
)
.unwrap();
let (registry, errors) = load_hooks_from_sources(
&[
HookSource::SettingsFile(&global_settings),
HookSource::SettingsFile(&claude_settings),
],
&[],
);
assert!(errors.is_empty());
// Both hooks should be loaded since they have different commands.
let hooks = registry.hooks_for(HookEventName::SessionStart);
assert_eq!(
hooks.len(),
2,
"expected 2 SessionStart hooks with different commands, got {}",
hooks.len()
);
}
#[test]
fn different_event_types_not_deduplicated() {
let dir = tempfile::tempdir().unwrap();
// Same command but different event types - should NOT be deduplicated.
let settings = dir.path().join("settings.json");
std::fs::write(
&settings,
r#"{
"hooks": {
"SessionStart": [{"hooks": [{"type": "command", "command": "hook.sh"}]}],
"SessionEnd": [{"hooks": [{"type": "command", "command": "hook.sh"}]}]
}
}"#,
)
.unwrap();
let (registry, errors) =
load_hooks_from_sources(&[HookSource::SettingsFile(&settings)], &[]);
assert!(errors.is_empty());
// Both hooks should be loaded since they're different event types.
assert_eq!(registry.hooks_for(HookEventName::SessionStart).len(), 1);
assert_eq!(registry.hooks_for(HookEventName::SessionEnd).len(), 1);
}
#[test]
fn same_command_in_same_directory_deduplicated() {
// When the same hook command is defined in multiple files within
// the same directory, they should be deduplicated (only the first
// one runs). This prevents accidental duplicate execution.
let dir = tempfile::tempdir().unwrap();
// Two files with the same hook command.
write_json(
dir.path(),
"01-first.json",
r#"{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"same.sh"}]}]}}"#,
);
write_json(
dir.path(),
"02-second.json",
r#"{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"same.sh"}]}]}}"#,
);
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty());
// Only one hook should be loaded (deduplicated by content).
let hooks = registry.hooks_for(HookEventName::SessionStart);
assert_eq!(
hooks.len(),
1,
"expected exactly 1 SessionStart hook after dedup, got {}",
hooks.len()
);
}
#[test]
fn realistic_claude_settings_discovery() {
let dir = tempfile::tempdir().unwrap();
// Simulate ~/.claude/settings.json with many extra keys.
let claude_settings = dir.path().join("settings.json");
std::fs::write(
&claude_settings,
r#"{
"model": "claude-sonnet-4-20250514",
"permissions": {"allow": ["Bash(npm test)"]},
"hooks": {
"PreToolUse": [
{"matcher": "Bash", "hooks": [{"type": "command", "command": "check.sh"}]}
]
},
"mcpServers": {"memory": {"command": "npx"}}
}"#,
)
.unwrap();
let (registry, errors) =
load_hooks_from_sources(&[HookSource::SettingsFile(&claude_settings)], &[]);
assert!(errors.is_empty(), "errors: {errors:?}");
assert_eq!(registry.len(), 1);
}
}

View file

@ -0,0 +1,895 @@
use crate::discovery::HookRegistry;
use crate::event::{HookEventEnvelope, HookEventName};
use crate::result::{HookDecision, HookRunResult};
use crate::runner::{self, HookRunnerResult, RunContext};
/// Result of a `pre_tool_use` dispatch: the final decision plus per-hook
/// execution details (for scrollback enrichment).
pub struct PreToolUseResult {
/// Final blocking decision (Allow or Deny).
pub decision: HookDecision,
/// Per-hook run results (includes HTTP info when applicable).
pub results: Vec<HookRunResult>,
}
/// Dispatch a `pre_tool_use` event against all matching hooks.
///
/// Runs hooks sequentially in config order. Only an explicit `deny`
/// decision from a hook stops the chain and blocks the tool call.
///
/// Hook failures (timeouts, crashes, command-not-found, env-var
/// pre-spawn refusals, malformed output) are **fail-open**: the failure
/// is logged and surfaced in the per-hook results for the UI scrollback,
/// but the tool call continues as if the hook had allowed it. Grok
/// runs in protected environments where induced-failure bypass of
/// security hooks is not part of the threat model; the previous
/// fail-closed posture over-blocked innocent tool calls when
/// hooks timed out or had unrelated configuration errors.
///
/// Returns `Allow` if no hooks match, all hooks allow, or all failing
/// hooks are non-blocking by virtue of this fail-open policy.
pub async fn dispatch_pre_tool_use(
registry: &HookRegistry,
envelope: &HookEventEnvelope,
ctx: &RunContext<'_>,
) -> PreToolUseResult {
let hooks = registry.hooks_for(HookEventName::PreToolUse);
if hooks.is_empty() {
return PreToolUseResult {
decision: HookDecision::Allow,
results: Vec::new(),
};
}
let span = tracing::info_span!(
"hooks.dispatch",
hook_event = %HookEventName::PreToolUse,
hook_count = hooks.len() as i64,
num_success = tracing::field::Empty,
num_failed = tracing::field::Empty,
num_blocking = tracing::field::Empty,
num_skipped = tracing::field::Empty,
total_duration_ms = tracing::field::Empty,
);
let _enter = span.enter();
let tool_name = extract_tool_name(envelope);
let mut run_results = Vec::new();
for spec in hooks {
if !spec.enabled || crate::trust::is_hook_disabled(&spec.name) {
tracing::info!(hook_name = %spec.name, "hook skipped (disabled)");
run_results.push(HookRunResult::Skipped {
hook_name: spec.name.clone(),
});
continue;
}
// Check matcher against tool name.
if let Some(ref matcher) = spec.matcher
&& let Some(ref name) = tool_name
&& !matcher.is_match(name)
{
continue;
}
let _hook_span = tracing::info_span!(
"hook.run",
hook_name = %spec.name,
hook_event = %HookEventName::PreToolUse,
)
.entered();
let (result, elapsed, http_info) = runner::run_hook(spec, envelope, ctx, true).await;
match result {
HookRunnerResult::Decision(HookDecision::Deny { reason, .. }) => {
tracing::info!(
hook_name = %spec.name,
elapsed_ms = elapsed.as_millis() as u64,
reason = %reason,
"hook denied"
);
run_results.push(HookRunResult::Failed {
hook_name: spec.name.clone(),
error: format!("denied: {reason}"),
elapsed,
http_info,
});
record_dispatch_counts(&span, &run_results, 1);
return PreToolUseResult {
decision: HookDecision::Deny {
reason,
hook_name: spec.name.clone(),
},
results: run_results,
};
}
HookRunnerResult::Decision(HookDecision::Allow) => {
tracing::info!(
hook_name = %spec.name,
elapsed_ms = elapsed.as_millis() as u64,
"hook allowed"
);
run_results.push(HookRunResult::Success {
hook_name: spec.name.clone(),
elapsed,
http_info,
});
}
// Fail-open: hook failures (timeouts, crashes, refusals to
// spawn, malformed output) are logged and recorded for the UI
// but do not deny the tool call. Only an explicit `deny`
// decision blocks. See module docs on dispatch_pre_tool_use
// for the rationale (protected-environment threat model).
HookRunnerResult::Failed(err) => {
tracing::warn!(
hook_name = %spec.name,
elapsed_ms = elapsed.as_millis() as u64,
error = %err,
"hook failed; ignoring (fail-open)"
);
run_results.push(HookRunResult::Failed {
hook_name: spec.name.clone(),
error: err.clone(),
elapsed,
http_info,
});
}
HookRunnerResult::Success => {
// Shouldn't happen for blocking hooks, but treat as allow.
tracing::info!(
hook_name = %spec.name,
elapsed_ms = elapsed.as_millis() as u64,
"hook completed"
);
run_results.push(HookRunResult::Success {
hook_name: spec.name.clone(),
elapsed,
http_info,
});
}
}
}
record_dispatch_counts(&span, &run_results, 0);
PreToolUseResult {
decision: HookDecision::Allow,
results: run_results,
}
}
/// Dispatch a non-blocking event (`session_start`, `post_tool_use`, `session_end`)
/// against all matching hooks.
///
/// Runs hooks sequentially, collects results. Never denies — callers log
/// results and continue.
pub async fn dispatch_non_blocking(
registry: &HookRegistry,
event: HookEventName,
envelope: &HookEventEnvelope,
ctx: &RunContext<'_>,
) -> Vec<HookRunResult> {
let hooks = registry.hooks_for(event);
if hooks.is_empty() {
return Vec::new();
}
let span = tracing::info_span!(
"hooks.dispatch",
hook_event = %event,
hook_count = hooks.len() as i64,
num_success = tracing::field::Empty,
num_failed = tracing::field::Empty,
num_blocking = tracing::field::Empty,
num_skipped = tracing::field::Empty,
total_duration_ms = tracing::field::Empty,
);
let _enter = span.enter();
let tool_name = extract_tool_name(envelope);
let mut results = Vec::with_capacity(hooks.len());
for spec in hooks {
if !spec.enabled || crate::trust::is_hook_disabled(&spec.name) {
tracing::info!(hook_name = %spec.name, "hook skipped (disabled)");
results.push(HookRunResult::Skipped {
hook_name: spec.name.clone(),
});
continue;
}
// Check matcher against tool name (only for tool events).
if let Some(ref matcher) = spec.matcher
&& let Some(ref name) = tool_name
&& !matcher.is_match(name)
{
continue;
}
let _hook_span = tracing::info_span!(
"hook.run",
hook_name = %spec.name,
hook_event = %event,
)
.entered();
let (result, elapsed, http_info) = runner::run_hook(spec, envelope, ctx, false).await;
match result {
HookRunnerResult::Success => {
tracing::info!(
hook_name = %spec.name,
elapsed_ms = elapsed.as_millis() as u64,
"hook completed"
);
results.push(HookRunResult::Success {
hook_name: spec.name.clone(),
elapsed,
http_info,
});
}
HookRunnerResult::Failed(err) => {
tracing::warn!(
hook_name = %spec.name,
elapsed_ms = elapsed.as_millis() as u64,
error = %err,
"hook failed"
);
results.push(HookRunResult::Failed {
hook_name: spec.name.clone(),
error: err,
elapsed,
http_info,
});
}
HookRunnerResult::Decision(_) => {
// Shouldn't happen for non-blocking hooks.
tracing::info!(
hook_name = %spec.name,
elapsed_ms = elapsed.as_millis() as u64,
"hook completed"
);
results.push(HookRunResult::Success {
hook_name: spec.name.clone(),
elapsed,
http_info,
});
}
}
}
record_dispatch_counts(&span, &results, 0);
results
}
/// Record hook outcome counts on the `hooks.dispatch` span. A blocking deny is
/// stored as a `Failed` result, so `num_blocking` is passed in and subtracted
/// from `num_failed` to avoid double-counting.
fn record_dispatch_counts(span: &tracing::Span, results: &[HookRunResult], num_blocking: i64) {
let mut num_success = 0i64;
let mut num_failed = 0i64;
let mut num_skipped = 0i64;
let mut total_duration_ms = 0i64;
for r in results {
match r {
HookRunResult::Success { elapsed, .. } => {
num_success += 1;
total_duration_ms += elapsed.as_millis() as i64;
}
HookRunResult::Failed { elapsed, .. } => {
num_failed += 1;
total_duration_ms += elapsed.as_millis() as i64;
}
HookRunResult::Skipped { .. } => num_skipped += 1,
}
}
span.record("num_success", num_success);
span.record("num_failed", num_failed - num_blocking);
span.record("num_blocking", num_blocking);
span.record("num_skipped", num_skipped);
span.record("total_duration_ms", total_duration_ms);
}
/// Build the hub custom hook `kind` string for a non-blocking hook event.
///
/// Returns `None` for `PreToolUse` (blocking, local-only). For all other
/// events the kind is `"hook.<snake_case_event_name>"`, derived from the
/// `Display` impl of `HookEventName`.
pub fn hub_hook_kind(event: HookEventName) -> Option<String> {
if event.is_blocking() {
return None;
}
Some(format!("hook.{event}"))
}
/// The tool name a matcher is tested against, or `None` for events with no tool
/// (lifecycle, prompt, compaction). `Notification` matches on its `notification_type`.
///
/// `tool_name` is the resolved underlying tool for meta-dispatch tools (`use_tool`
/// and the external MCP-call tool), so a matcher keyed on the real tool fires directly.
pub fn extract_tool_name(envelope: &HookEventEnvelope) -> Option<String> {
use crate::event::HookPayload;
match &envelope.payload {
HookPayload::PreToolUse { tool_name, .. } => Some(tool_name.clone()),
HookPayload::PostToolUse { tool_name, .. } => Some(tool_name.clone()),
HookPayload::PostToolUseFailure { tool_name, .. } => Some(tool_name.clone()),
HookPayload::PermissionDenied { tool_name, .. } => Some(tool_name.clone()),
HookPayload::Notification {
notification_type, ..
} => Some(notification_type.clone()),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::HookSpec;
use crate::event::{HookEventEnvelope, HookEventName, HookPayload};
use crate::matcher::HookMatcher;
use std::collections::HashMap;
use std::path::PathBuf;
/// Helper: build a pre_tool_use envelope for the given tool name.
fn pre_tool_use_envelope(tool_name: &str) -> HookEventEnvelope {
HookEventEnvelope {
hook_event_name: HookEventName::PreToolUse,
session_id: "test-session".into(),
cwd: "/tmp".into(),
workspace_root: "/tmp".into(),
timestamp: "2025-01-01T00:00:00Z".into(),
transcript_path: None,
client_identifier: None,
prompt_id: None,
payload: HookPayload::PreToolUse {
tool_name: tool_name.into(),
tool_use_id: "tu-1".into(),
tool_input: serde_json::json!({"command": "ls"}),
tool_input_truncated: false,
permission_mode: None,
subagent_type: None,
},
}
}
/// Helper: build a session_start envelope.
fn session_start_envelope() -> HookEventEnvelope {
HookEventEnvelope {
hook_event_name: HookEventName::SessionStart,
session_id: "test-session".into(),
cwd: "/tmp".into(),
workspace_root: "/tmp".into(),
timestamp: "2025-01-01T00:00:00Z".into(),
transcript_path: None,
client_identifier: None,
prompt_id: None,
payload: HookPayload::SessionStart {
source: "new".into(),
model_id: None,
agent_type: None,
},
}
}
fn run_ctx() -> RunContext<'static> {
RunContext {
session_id: "test-session",
workspace_root: "/tmp",
}
}
/// Helper: create a HookSpec pointing at `sh -c '<script>'` that prints
/// the given JSON and exits with the given code.
fn make_command_spec(
name: &str,
matcher: Option<&str>,
enabled: bool,
script: &str,
) -> HookSpec {
HookSpec {
name: name.into(),
event: HookEventName::PreToolUse,
handler_type: "command".into(),
configured_matcher: matcher.map(|s| s.to_string()),
matcher: matcher.map(|s| HookMatcher::new(s).unwrap()),
enabled,
command: Some(PathBuf::from(script)),
command_raw: Some(script.to_string()),
url: None,
url_raw: None,
timeout_ms: 5000,
source_dir: PathBuf::from("/tmp"),
extra_env: HashMap::new(),
}
}
/// Build a registry from a list of specs using the public API.
fn registry_from_specs(specs: Vec<HookSpec>) -> HookRegistry {
let (mut registry, _) = crate::discovery::load_hooks(None, None);
registry.append_specs(specs);
registry
}
// ── extract_tool_name tests ──────────────────────────────────
#[test]
fn extract_tool_name_from_pre_tool_use() {
let envelope = pre_tool_use_envelope("run_terminal_cmd");
assert_eq!(
extract_tool_name(&envelope),
Some("run_terminal_cmd".into())
);
}
#[test]
fn extract_tool_name_from_session_start_is_none() {
let envelope = session_start_envelope();
assert_eq!(extract_tool_name(&envelope), None);
}
#[test]
fn extract_tool_name_from_notification() {
let envelope = HookEventEnvelope {
hook_event_name: HookEventName::Notification,
session_id: "s".into(),
cwd: "/tmp".into(),
workspace_root: "/tmp".into(),
timestamp: "t".into(),
transcript_path: None,
client_identifier: None,
prompt_id: None,
payload: HookPayload::Notification {
notification_type: "permission_prompt".into(),
message: None,
title: None,
level: None,
},
};
assert_eq!(
extract_tool_name(&envelope),
Some("permission_prompt".into())
);
}
// ── dispatch_pre_tool_use tests ──────────────────────────────
#[tokio::test]
async fn empty_registry_allows() {
let registry = registry_from_specs(vec![]);
let envelope = pre_tool_use_envelope("run_terminal_cmd");
let result = dispatch_pre_tool_use(&registry, &envelope, &run_ctx()).await;
assert_eq!(result.decision, HookDecision::Allow);
}
#[tokio::test]
async fn single_allow_hook() {
let spec = make_command_spec("allow-hook", None, true, "echo '{\"decision\":\"allow\"}'");
let registry = registry_from_specs(vec![spec]);
let envelope = pre_tool_use_envelope("run_terminal_cmd");
let result = dispatch_pre_tool_use(&registry, &envelope, &run_ctx()).await;
assert_eq!(result.decision, HookDecision::Allow);
}
#[tokio::test]
async fn single_deny_hook() {
let spec = make_command_spec(
"deny-hook",
None,
true,
"echo '{\"decision\":\"deny\",\"reason\":\"blocked\"}'; exit 2",
);
let registry = registry_from_specs(vec![spec]);
let envelope = pre_tool_use_envelope("run_terminal_cmd");
let result = dispatch_pre_tool_use(&registry, &envelope, &run_ctx()).await;
match result.decision {
HookDecision::Deny {
ref reason,
ref hook_name,
} => {
assert_eq!(reason, "blocked");
assert_eq!(hook_name, "deny-hook");
}
ref other => panic!("expected Deny, got {other:?}"),
}
}
#[tokio::test]
async fn disabled_hook_is_skipped_allows() {
// A deny hook that is disabled should be skipped entirely.
let spec = make_command_spec(
"disabled-deny",
None,
false, // disabled!
"echo '{\"decision\":\"deny\",\"reason\":\"should not run\"}'; exit 2",
);
let registry = registry_from_specs(vec![spec]);
let envelope = pre_tool_use_envelope("run_terminal_cmd");
let result = dispatch_pre_tool_use(&registry, &envelope, &run_ctx()).await;
assert_eq!(result.decision, HookDecision::Allow);
}
#[tokio::test]
async fn matcher_skips_non_matching_tool() {
// Deny hook with matcher for "read_file" should not fire for "run_terminal_cmd".
let spec = make_command_spec(
"read-only-deny",
Some("read_file"),
true,
"echo '{\"decision\":\"deny\",\"reason\":\"blocked\"}'; exit 2",
);
let registry = registry_from_specs(vec![spec]);
let envelope = pre_tool_use_envelope("run_terminal_cmd");
let result = dispatch_pre_tool_use(&registry, &envelope, &run_ctx()).await;
assert_eq!(result.decision, HookDecision::Allow);
}
#[tokio::test]
async fn matcher_fires_on_matching_tool() {
// Deny hook with matcher for "run_terminal_cmd" should fire.
let spec = make_command_spec(
"bash-deny",
Some("run_terminal_cmd"),
true,
"echo '{\"decision\":\"deny\",\"reason\":\"bash blocked\"}'; exit 2",
);
let registry = registry_from_specs(vec![spec]);
let envelope = pre_tool_use_envelope("run_terminal_cmd");
let result = dispatch_pre_tool_use(&registry, &envelope, &run_ctx()).await;
match result.decision {
HookDecision::Deny { ref reason, .. } => assert_eq!(reason, "bash blocked"),
ref other => panic!("expected Deny, got {other:?}"),
}
}
#[tokio::test]
async fn first_deny_wins_short_circuits() {
// Two hooks: first denies, second allows. First deny should win.
let deny_spec = make_command_spec(
"first-deny",
None,
true,
"echo '{\"decision\":\"deny\",\"reason\":\"first says no\"}'; exit 2",
);
let allow_spec = make_command_spec(
"second-allow",
None,
true,
"echo '{\"decision\":\"allow\"}'",
);
let registry = registry_from_specs(vec![deny_spec, allow_spec]);
let envelope = pre_tool_use_envelope("run_terminal_cmd");
let result = dispatch_pre_tool_use(&registry, &envelope, &run_ctx()).await;
match result.decision {
HookDecision::Deny {
ref reason,
ref hook_name,
..
} => {
assert_eq!(reason, "first says no");
assert_eq!(hook_name, "first-deny");
}
ref other => panic!("expected Deny, got {other:?}"),
}
}
#[tokio::test]
async fn allow_then_deny_denies() {
// First hook allows, second hook denies. The deny should win.
// This is the key "stricter deny filter takes precedence" scenario.
let allow_spec =
make_command_spec("broad-allow", None, true, "echo '{\"decision\":\"allow\"}'");
let deny_spec = make_command_spec(
"strict-deny",
None,
true,
"echo '{\"decision\":\"deny\",\"reason\":\"strict policy\"}'; exit 2",
);
let registry = registry_from_specs(vec![allow_spec, deny_spec]);
let envelope = pre_tool_use_envelope("run_terminal_cmd");
let result = dispatch_pre_tool_use(&registry, &envelope, &run_ctx()).await;
match result.decision {
HookDecision::Deny {
ref reason,
ref hook_name,
..
} => {
assert_eq!(reason, "strict policy");
assert_eq!(hook_name, "strict-deny");
}
ref other => panic!("expected Deny from strict filter, got {other:?}"),
}
}
#[tokio::test]
async fn allow_broad_deny_specific_tool_match() {
// Broad allow hook (no matcher), specific deny hook for "run_terminal_cmd".
// The deny should fire for matching tool even though allow came first.
let allow_spec =
make_command_spec("allow-all", None, true, "echo '{\"decision\":\"allow\"}'");
let deny_spec = make_command_spec(
"deny-bash",
Some("run_terminal_cmd"),
true,
"echo '{\"decision\":\"deny\",\"reason\":\"bash not allowed\"}'; exit 2",
);
let registry = registry_from_specs(vec![allow_spec, deny_spec]);
let envelope = pre_tool_use_envelope("run_terminal_cmd");
let result = dispatch_pre_tool_use(&registry, &envelope, &run_ctx()).await;
match result.decision {
HookDecision::Deny { ref reason, .. } => assert_eq!(reason, "bash not allowed"),
ref other => panic!("expected Deny, got {other:?}"),
}
}
#[tokio::test]
async fn allow_broad_deny_specific_non_matching_allows() {
// Broad allow hook, specific deny for "read_file" only.
// Calling with "run_terminal_cmd" should allow (deny doesn't match).
let allow_spec =
make_command_spec("allow-all", None, true, "echo '{\"decision\":\"allow\"}'");
let deny_spec = make_command_spec(
"deny-read",
Some("read_file"),
true,
"echo '{\"decision\":\"deny\",\"reason\":\"no read\"}'; exit 2",
);
let registry = registry_from_specs(vec![allow_spec, deny_spec]);
let envelope = pre_tool_use_envelope("run_terminal_cmd");
let result = dispatch_pre_tool_use(&registry, &envelope, &run_ctx()).await;
assert_eq!(result.decision, HookDecision::Allow);
}
#[tokio::test]
async fn fail_open_on_hook_crash() {
// Hook exits with code 1 (crash). Under fail-open the tool call
// should still be allowed; the failure is recorded for the UI.
let spec = make_command_spec("crasher", None, true, "exit 1");
let registry = registry_from_specs(vec![spec]);
let envelope = pre_tool_use_envelope("run_terminal_cmd");
let result = dispatch_pre_tool_use(&registry, &envelope, &run_ctx()).await;
assert_eq!(
result.decision,
HookDecision::Allow,
"fail-open: a crashing hook must not block the tool call"
);
assert_eq!(result.results.len(), 1);
assert!(
matches!(&result.results[0], HookRunResult::Failed { hook_name, .. } if hook_name == "crasher"),
"the failure must still appear in run_results for UI scrollback, got {:?}",
result.results
);
}
#[tokio::test]
async fn fail_open_then_deny_lets_deny_win() {
// First hook crashes (now fail-open), second denies. Under
// fail-open the chain continues past the crash and the second
// hook's explicit deny is what blocks the call.
let crash_spec = make_command_spec("crasher", None, true, "exit 1");
let deny_spec = make_command_spec(
"denier",
None,
true,
"echo '{\"decision\":\"deny\",\"reason\":\"nope\"}'; exit 2",
);
let registry = registry_from_specs(vec![crash_spec, deny_spec]);
let envelope = pre_tool_use_envelope("run_terminal_cmd");
let result = dispatch_pre_tool_use(&registry, &envelope, &run_ctx()).await;
match result.decision {
HookDecision::Deny {
ref hook_name,
ref reason,
} => {
assert_eq!(hook_name, "denier");
assert_eq!(reason, "nope");
}
ref other => panic!("expected Deny from explicit denier, got {other:?}"),
}
// Both hooks ran: the crasher recorded a Failed result, the
// denier recorded a Failed result with "denied: nope" prefix.
assert_eq!(result.results.len(), 2);
}
#[tokio::test]
async fn all_hooks_allow_results_in_allow() {
let specs = vec![
make_command_spec("a1", None, true, "echo '{\"decision\":\"allow\"}'"),
make_command_spec("a2", None, true, "echo '{\"decision\":\"allow\"}'"),
make_command_spec("a3", None, true, "echo '{\"decision\":\"allow\"}'"),
];
let registry = registry_from_specs(specs);
let envelope = pre_tool_use_envelope("run_terminal_cmd");
let result = dispatch_pre_tool_use(&registry, &envelope, &run_ctx()).await;
assert_eq!(result.decision, HookDecision::Allow);
}
#[tokio::test]
async fn mixed_disabled_and_deny() {
// Disabled deny hook followed by enabled allow. Should allow.
let disabled_deny = make_command_spec(
"disabled-deny",
None,
false,
"echo '{\"decision\":\"deny\",\"reason\":\"should not run\"}'; exit 2",
);
let enabled_allow = make_command_spec(
"enabled-allow",
None,
true,
"echo '{\"decision\":\"allow\"}'",
);
let registry = registry_from_specs(vec![disabled_deny, enabled_allow]);
let envelope = pre_tool_use_envelope("run_terminal_cmd");
let result = dispatch_pre_tool_use(&registry, &envelope, &run_ctx()).await;
assert_eq!(result.decision, HookDecision::Allow);
}
// ── fail-open regression tests ───────────────────────────────
#[tokio::test]
async fn fail_open_records_error_in_run_results() {
// A hook that returns malformed output and exits non-zero now
// results in Allow (fail-open) but the failure detail is still
// captured in run_results for the UI scrollback.
let spec = make_command_spec("bad-output", None, true, "echo 'not json'; exit 1");
let registry = registry_from_specs(vec![spec]);
let envelope = pre_tool_use_envelope("run_terminal_cmd");
let result = dispatch_pre_tool_use(&registry, &envelope, &run_ctx()).await;
assert_eq!(
result.decision,
HookDecision::Allow,
"fail-open: bad output must not block the tool call"
);
assert_eq!(result.results.len(), 1);
match &result.results[0] {
HookRunResult::Failed {
hook_name, error, ..
} => {
assert_eq!(hook_name, "bad-output");
assert!(
error.contains("bad-output") || error.contains("exit code"),
"error detail should be preserved for UI: {error}"
);
}
other => panic!("expected Failed run result, got {other:?}"),
}
}
// ── dispatch_non_blocking tests ──────────────────────────────
#[tokio::test]
async fn non_blocking_empty_registry() {
let registry = registry_from_specs(vec![]);
let envelope = session_start_envelope();
let results = dispatch_non_blocking(
&registry,
HookEventName::SessionStart,
&envelope,
&run_ctx(),
)
.await;
assert!(results.is_empty());
}
#[tokio::test]
async fn non_blocking_disabled_hook_skipped() {
let mut spec = make_command_spec("disabled", None, false, "echo ok");
spec.event = HookEventName::SessionStart;
let registry = registry_from_specs(vec![spec]);
let envelope = session_start_envelope();
let results = dispatch_non_blocking(
&registry,
HookEventName::SessionStart,
&envelope,
&run_ctx(),
)
.await;
assert_eq!(results.len(), 1);
assert!(matches!(results[0], HookRunResult::Skipped { .. }));
}
#[tokio::test]
async fn non_blocking_success() {
let mut spec = make_command_spec("starter", None, true, "echo ok");
spec.event = HookEventName::SessionStart;
let registry = registry_from_specs(vec![spec]);
let envelope = session_start_envelope();
let results = dispatch_non_blocking(
&registry,
HookEventName::SessionStart,
&envelope,
&run_ctx(),
)
.await;
assert_eq!(results.len(), 1);
assert!(matches!(results[0], HookRunResult::Success { .. }));
}
#[tokio::test]
async fn non_blocking_failure_does_not_stop_chain() {
let mut spec1 = make_command_spec("crasher", None, true, "exit 1");
spec1.event = HookEventName::SessionStart;
let mut spec2 = make_command_spec("ok", None, true, "echo ok");
spec2.event = HookEventName::SessionStart;
let registry = registry_from_specs(vec![spec1, spec2]);
let envelope = session_start_envelope();
let results = dispatch_non_blocking(
&registry,
HookEventName::SessionStart,
&envelope,
&run_ctx(),
)
.await;
assert_eq!(results.len(), 2);
assert!(matches!(results[0], HookRunResult::Failed { .. }));
assert!(matches!(results[1], HookRunResult::Success { .. }));
}
// ── hub_hook_kind tests ──────────────────────────────────────
#[test]
fn hub_hook_kind_returns_none_for_pre_tool_use() {
assert_eq!(hub_hook_kind(HookEventName::PreToolUse), None);
}
#[test]
fn hub_hook_kind_maps_all_non_blocking_events() {
let cases: &[(HookEventName, &str)] = &[
(HookEventName::SessionStart, "hook.session_start"),
(HookEventName::SessionEnd, "hook.session_end"),
(HookEventName::Stop, "hook.stop"),
(HookEventName::StopFailure, "hook.stop_failure"),
(HookEventName::PostToolUse, "hook.post_tool_use"),
(
HookEventName::PostToolUseFailure,
"hook.post_tool_use_failure",
),
(HookEventName::PermissionDenied, "hook.permission_denied"),
(HookEventName::UserPromptSubmit, "hook.user_prompt_submit"),
(HookEventName::Notification, "hook.notification"),
(HookEventName::SubagentStart, "hook.subagent_start"),
(HookEventName::SubagentStop, "hook.subagent_stop"),
(HookEventName::SubagentEnd, "hook.subagent_stop"),
(HookEventName::PreCompact, "hook.pre_compact"),
(HookEventName::PostCompact, "hook.post_compact"),
];
// Exhaustive match — adding a new HookEventName variant causes a
// compiler error here, forcing this test to be updated.
let total_variants = |e: HookEventName| -> usize {
match e {
HookEventName::SessionStart
| HookEventName::SessionEnd
| HookEventName::Stop
| HookEventName::StopFailure
| HookEventName::PreToolUse
| HookEventName::PostToolUse
| HookEventName::PostToolUseFailure
| HookEventName::PermissionDenied
| HookEventName::UserPromptSubmit
| HookEventName::Notification
| HookEventName::SubagentStart
| HookEventName::SubagentStop
| HookEventName::SubagentEnd
| HookEventName::PreCompact
| HookEventName::PostCompact => 15,
}
};
assert_eq!(
cases.len() + 1, // +1 for PreToolUse (blocking, tested separately)
total_variants(HookEventName::SessionStart),
"update hub_hook_kind test when new HookEventName variants are added"
);
for (event, expected) in cases {
let kind = hub_hook_kind(*event);
assert_eq!(
kind.as_deref(),
Some(*expected),
"hub_hook_kind wrong for {event:?}"
);
}
}
}

View file

@ -0,0 +1,856 @@
//! Environment variable expansion helper for hook config strings.
//!
//! Provides `${VAR}` / `$VAR` substitution that prefers a per-hook
//! `extra_env` map over the process environment. Used by:
//!
//! * the JSON hook parser ([`crate::config::parse_hook_file`]) to expand
//! `command` and `url` fields at config-load time, and
//! * the HTTP runner ([`crate::runner::http`]) to expand `spec.url` once
//! more right before SSRF validation, so plugin URLs that reference
//! plugin-injected vars (e.g. `${CLAUDE_PLUGIN_ROOT}/check`) resolve.
//!
//! The expansion is **lossless on missing vars and on every parameter-
//! expansion-modifier form** -- both unset plain references (e.g.
//! `${UNSET}/x`) AND any modifier form (e.g. `${VAR:-default}`,
//! `${VAR%pat}`, see the "Parameter-expansion forms" paragraph below)
//! are preserved verbatim. This is important so that:
//!
//! * config-load-time expansion is idempotent (re-running it on an already
//! expanded string is a no-op),
//! * vars that are intentionally deferred to runtime (set later by the
//! shell, the dispatcher, or `extra_env`) survive the load-time pass and
//! are caught by the runtime pre-flight check in
//! [`crate::runner::command`] if they remain unset at execution, and
//! * shell-specific modifier semantics (especially `${VAR:-x}` for
//! set-but-empty values) stay the responsibility of the runtime
//! `sh -c` branch where they apply correctly.
//!
//! Parameter-expansion forms (`${VAR:-default}`, `${VAR-default}`,
//! `${VAR:=x}`, `${VAR:?msg}`, `${VAR:+x}`, `${VAR%pat}`, `${VAR#pat}`,
//! `${VAR/pat/repl}`, `${VAR:N}`, `${VAR:N:M}`) are also preserved
//! verbatim. These forms have shell-specific semantics (notably the
//! "set-but-empty" behaviour of `:-` differs between `sh` and the
//! shellexpand crate) that the runtime `sh -c` branch resolves
//! correctly. Mirroring the modifier-skip behaviour in
//! [`crate::runner::command::find_unresolved_env_vars`] keeps the two
//! layers in sync: the user wrote the modifier form because they wanted
//! the shell's interpretation, so we leave it for the shell.
//!
//! Same underlying engine (`shellexpand::env_with_context_no_errors`)
//! and same lossless-on-missing semantics as
//! `xai_grok_config::expand_env_vars_in_string`, but with an additional
//! per-hook `extra` map consulted before process env, and with the
//! parameter-expansion-modifier preservation described above.
//!
//! ## Asymmetry between `command` and `url`
//!
//! Load-time expansion in [`crate::config::parse_hook_file`] runs once
//! using a snapshot of process env at parse time. The HTTP runner does
//! a second pass at runtime so plugin-injected vars that arrive in
//! `extra_env` after parsing (e.g. `CLAUDE_PLUGIN_ROOT`) resolve, and
//! so mid-session changes to process env are picked up for URLs.
//! Command paths are NOT re-expanded at runtime; the runtime `sh -c`
//! branch in [`crate::runner::command`] picks up mid-session env
//! changes for commands that contain shell metacharacters, but
//! direct-exec paths see only the parse-time snapshot. Document this
//! contract on `HookSpec::command` / `HookSpec::url`.
use std::collections::HashMap;
/// Sentinel prefix for the per-call mask sentinel; see [`make_sentinel`].
///
/// Uses a Unicode Private Use Area code point (`U+F8FF`, the
/// "Apple logo" PUA char) plus a long magic ASCII prefix. The full
/// sentinel string adds 128 bits of per-call entropy as a hex suffix
/// followed by another `U+F8FF` char.
const SENTINEL_PREFIX: &str = "\u{f8ff}__GROK_HOOKS_MASK_";
const SENTINEL_SUFFIX: &str = "__\u{f8ff}";
/// Build a per-call sentinel string used to hide modifier-form
/// `${...}` substrings from `shellexpand::env_with_context_no_errors`.
/// The sentinel is restored to `${` after shellexpand runs, so the
/// modifier form survives expansion verbatim.
///
/// The sentinel is randomized on every call: 128 bits of entropy
/// from `fastrand` are formatted as hex between the fixed
/// [`SENTINEL_PREFIX`] / [`SENTINEL_SUFFIX`] markers. The chance of
/// a natural collision with arbitrary user-supplied input or a
/// modifier body is ~2^-128, removing the sentinel-substring
/// rewrite hazard that a fixed-string sentinel had.
///
/// Properties:
///
/// * **Unambiguous** -- per-call randomization makes accidental
/// collision with any real hook command/URL string or value
/// extracted from `extra_env` vanishingly unlikely.
/// * **UTF-8 safe** -- the leading and trailing PUA chars are 3-byte
/// UTF-8 sequences; the middle is ASCII hex.
/// * **Visually distinct in panic messages / logs** if a sentinel
/// ever escapes back to the user (it shouldn't, but if it does
/// the magic string makes triage immediate).
///
/// Replaces a previous fixed sentinel (and an even earlier 2-NUL-byte
/// sentinel `"\u{0}\u{0}"`) which could collide with a hand-crafted
/// `extra_env` value or modifier body containing the same byte
/// sequence; see the
/// `mask_helper_preserves_pre_existing_old_nul_sentinel`,
/// `expand_preserves_pre_existing_legacy_fixed_sentinel_in_extra`,
/// and related regression tests which construct legacy collision
/// inputs and assert they are preserved verbatim.
fn make_sentinel() -> String {
let hi: u64 = fastrand::u64(..);
let lo: u64 = fastrand::u64(..);
format!("{SENTINEL_PREFIX}{hi:016x}{lo:016x}{SENTINEL_SUFFIX}")
}
/// Expand `${VAR}` / `$VAR` references in `input`.
///
/// Lookup order for each reference:
/// 1. `extra` (the per-hook `extra_env` map)
/// 2. The current process environment
///
/// Unresolved references are preserved verbatim so this function is safe
/// to call repeatedly (idempotent on already-expanded strings) and so
/// references that are intentionally resolved at runtime (e.g. by the
/// dispatcher's always-set `GROK_HOOK_*` vars) survive the load-time pass.
///
/// Parameter-expansion-modifier forms (`${VAR:-x}`, `${VAR%pat}`, etc.)
/// are ALSO preserved verbatim; see the module-level rustdoc for why.
pub(crate) fn expand_env_vars_with_extra(input: &str, extra: &HashMap<String, String>) -> String {
// Generate a fresh per-call sentinel. 128 bits of entropy means a
// natural collision with any input substring or extra-env value is
// ~2^-128 probability. See `make_sentinel` rustdoc.
let sentinel = make_sentinel();
// Defence in depth: if the freshly-generated sentinel ever happens
// to appear in the input or in any extra-env value (vanishingly
// unlikely; would require an adversary to predict our PRNG output),
// panic in debug builds and fall through to legacy behaviour in
// release. Returning the input unchanged is safer than rewriting a
// legitimate substring to `${`.
debug_assert!(
!input.contains(&sentinel) && !extra.values().any(|v| v.contains(&sentinel)),
"per-call sentinel collided with input or extra-env value"
);
// Step 1: hide any `${VAR<modifier>...}` substring from shellexpand by
// replacing the leading `${` with the per-call sentinel. shellexpand's
// grammar requires `$` before a brace to recognize the form, so
// replacing the leading `${` with a non-`$` sentinel makes the body
// look like literal text to the expander.
let masked = mask_modifier_forms(input, &sentinel);
// Step 2: run shellexpand on the (possibly) masked input.
let context = |name: &str| -> Option<String> {
if let Some(v) = extra.get(name) {
return Some(v.clone());
}
std::env::var(name).ok()
};
let expanded = shellexpand::env_with_context_no_errors(&masked, context).into_owned();
// Step 3: restore the sentinels back to `${`. Because the sentinel is
// freshly randomized per call, the only way it appears in `expanded`
// is if `mask_modifier_forms` put it there.
if expanded.contains(&sentinel) {
expanded.replace(&sentinel, "${")
} else {
expanded
}
}
/// Walk `input` and, for every `${...}` substring whose contents are a
/// valid identifier followed by a parameter-expansion modifier, replace
/// the leading `${` with `sentinel`. Plain `${VAR}` and bare `$VAR`
/// references are NOT touched -- they are passed through to shellexpand
/// for normal resolution.
///
/// "Modifier" here means anything inside the braces after the
/// identifier name: `:-`, `-`, `:=`, `=`, `:?`, `?`, `:+`, `+`, `%`,
/// `#`, `/`, `:N` (digit), `:N:M`, etc. This shares its detection
/// logic with [`crate::runner::command::find_unresolved_env_vars`] via
/// [`iter_env_var_references`].
fn mask_modifier_forms(input: &str, sentinel: &str) -> String {
let mut out = String::with_capacity(input.len());
let mut cursor: usize = 0;
for r in iter_env_var_references(input) {
// Copy any literal text between the previous reference (or
// start of string) and this one verbatim.
if cursor < r.start {
out.push_str(&input[cursor..r.start]);
}
// Modifier-form braced ref: replace leading `${` with sentinel
// and emit the body (including closing `}`) as-is.
if r.braced && r.has_modifier {
out.push_str(sentinel);
// body_start = r.start + 2 (past `${`); copy up to and
// including the closing `}` at r.end - 1.
out.push_str(&input[r.start + 2..r.end]);
} else {
// Plain `${NAME}`, bare `$NAME`, or invalid form: pass
// through verbatim so shellexpand can resolve (or leave
// unresolved).
out.push_str(&input[r.start..r.end]);
}
cursor = r.end;
}
// Copy the trailing literal tail.
if cursor < input.len() {
out.push_str(&input[cursor..]);
}
out
}
/// One detected env-var reference in a string, as produced by
/// [`iter_env_var_references`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct EnvVarRef<'a> {
/// Byte offset where the leading `$` starts.
pub start: usize,
/// Byte offset one past the end of the reference. For braced
/// forms this is one past the closing `}`; for bare forms it is
/// one past the last identifier character.
pub end: usize,
/// Identifier name. For `${VAR...}` and `$VAR` this is `"VAR"`;
/// for invalid forms (e.g. `${:-foo}`, `${}`) it is empty.
pub name: &'a str,
/// True for `${...}` (braced); false for `$NAME` (bare).
pub braced: bool,
/// True if the braced form contains a parameter-expansion
/// modifier between the identifier and the closing `}`
/// (`:`, `-`, `=`, `?`, `+`, `%`, `#`, `/`, digit suffix, etc.).
/// Always false for bare references and for invalid braced forms.
pub has_modifier: bool,
}
/// Walk `input` and yield every `$VAR` / `${...}` reference. Skips
/// shell positional / special params (`$1`, `$$`, `$?`, `$#`,
/// `$(...)`, `$@`, etc.) since none of those are env-var references.
///
/// Behaviour notes:
///
/// * Unterminated braced forms (`${VAR:-no-close`) are skipped: the
/// `$` is consumed and scanning continues at the next byte. This
/// matches `shellexpand`'s behaviour of treating unterminated
/// forms as literal text.
/// * Nested braces inside a modifier body (`${A:-${B}}`) are handled
/// by matching the FIRST `}` -- the inner `${B}` becomes part of
/// the outer modifier body. This mirrors the legacy parser
/// behaviour (and the runtime `sh -c` branch handles real nesting
/// natively when the form reaches the shell).
/// * Empty / invalid identifier (`${}`, `${:-foo}`) is yielded with
/// an empty `name`, so callers can decide whether to mask it.
pub(crate) fn iter_env_var_references(input: &str) -> EnvVarRefIter<'_> {
EnvVarRefIter { input, pos: 0 }
}
pub(crate) struct EnvVarRefIter<'a> {
input: &'a str,
pos: usize,
}
impl<'a> Iterator for EnvVarRefIter<'a> {
type Item = EnvVarRef<'a>;
fn next(&mut self) -> Option<Self::Item> {
let bytes = self.input.as_bytes();
while self.pos < bytes.len() {
if bytes[self.pos] != b'$' {
self.pos += 1;
continue;
}
let dollar = self.pos;
// Past-the-`$` index.
let after = dollar + 1;
if after >= bytes.len() {
// Trailing lone `$` -- not a reference. Stop.
self.pos = bytes.len();
return None;
}
if bytes[after] == b'{' {
// Braced form: ${...}
let body_start = after + 1;
// Read identifier prefix (alphanumeric / underscore).
let mut name_end = body_start;
while name_end < bytes.len()
&& (bytes[name_end].is_ascii_alphanumeric() || bytes[name_end] == b'_')
{
name_end += 1;
}
// Find the FIRST closing `}` from the identifier end.
let mut close = name_end;
while close < bytes.len() && bytes[close] != b'}' {
close += 1;
}
if close >= bytes.len() {
// Unterminated brace -- not a real form. Skip the
// `$` and keep scanning.
self.pos = dollar + 1;
continue;
}
let name = std::str::from_utf8(&bytes[body_start..name_end]).unwrap_or("");
let has_modifier = !name.is_empty() && name_end < close;
let end = close + 1;
self.pos = end;
return Some(EnvVarRef {
start: dollar,
end,
name,
braced: true,
has_modifier,
});
}
// Bare `$NAME`: identifier must start with letter / `_`.
// Anything else (`$1`, `$$`, `$?`, `$#`, `$(`, etc.) is a
// shell special and not an env-var reference.
if bytes[after].is_ascii_alphabetic() || bytes[after] == b'_' {
let start_id = after;
let mut end_id = start_id;
while end_id < bytes.len()
&& (bytes[end_id].is_ascii_alphanumeric() || bytes[end_id] == b'_')
{
end_id += 1;
}
let name = std::str::from_utf8(&bytes[start_id..end_id]).unwrap_or("");
self.pos = end_id;
return Some(EnvVarRef {
start: dollar,
end: end_id,
name,
braced: false,
has_modifier: false,
});
}
// `$` followed by a non-identifier, non-`{` byte. Skip
// both bytes and continue.
self.pos = after + 1;
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::with_env_var;
#[test]
fn expands_braced_var_from_extra() {
let mut extra = HashMap::new();
extra.insert("PLUGIN_HOST".to_string(), "example.com".to_string());
let out = expand_env_vars_with_extra("https://${PLUGIN_HOST}/check", &extra);
assert_eq!(out, "https://example.com/check");
}
#[test]
fn expands_bare_var_from_extra() {
let mut extra = HashMap::new();
extra.insert("ROOT".to_string(), "/opt/plugin".to_string());
let out = expand_env_vars_with_extra("$ROOT/bin/x.sh", &extra);
assert_eq!(out, "/opt/plugin/bin/x.sh");
}
#[test]
fn extra_takes_precedence_over_process_env() {
with_env_var(
"GROK_HOOKS_ENV_EXPAND_TEST_PRECEDENCE",
Some("from-process"),
|| {
let mut extra = HashMap::new();
extra.insert(
"GROK_HOOKS_ENV_EXPAND_TEST_PRECEDENCE".to_string(),
"from-extra".to_string(),
);
let out =
expand_env_vars_with_extra("${GROK_HOOKS_ENV_EXPAND_TEST_PRECEDENCE}", &extra);
assert_eq!(out, "from-extra");
},
);
}
#[test]
fn falls_back_to_process_env() {
with_env_var(
"GROK_HOOKS_ENV_EXPAND_TEST_FALLBACK",
Some("/from/proc/env"),
|| {
let extra = HashMap::new();
let out =
expand_env_vars_with_extra("${GROK_HOOKS_ENV_EXPAND_TEST_FALLBACK}/x", &extra);
assert_eq!(out, "/from/proc/env/x");
},
);
}
#[test]
fn preserves_unresolved_references() {
// shellexpand's no-errors variant returns the original `${VAR}` text
// when the var is unset in both `extra` and the process env. This
// makes load-time expansion idempotent and lets runtime-only vars
// survive the pass to be caught by `find_unresolved_env_vars`.
with_env_var("GROK_HOOKS_ENV_EXPAND_NEVER_SET", None, || {
let extra = HashMap::new();
let input = "${GROK_HOOKS_ENV_EXPAND_NEVER_SET}/x.sh";
let out = expand_env_vars_with_extra(input, &extra);
assert_eq!(out, input);
});
}
#[test]
fn idempotent_on_already_expanded_string() {
let extra = HashMap::new();
let already = "/opt/plugins/foo/hooks/x.sh";
let out = expand_env_vars_with_extra(already, &extra);
assert_eq!(out, already);
}
#[test]
fn empty_input_returns_empty() {
let extra = HashMap::new();
assert_eq!(expand_env_vars_with_extra("", &extra), "");
}
// ── Parameter-expansion-modifier preservation ───────────────
/// `${VAR:-default}` must be preserved verbatim, even when `VAR` is
/// unset at expand time. Otherwise shellexpand resolves to the
/// literal default and the runtime branch never gets a chance to
/// see `VAR`'s real (runtime-only) value.
#[test]
fn preserves_default_modifier_when_var_unset() {
let extra = HashMap::new();
with_env_var("GROK_HOOKS_ENV_EXPAND_MODIFIER_UNSET", None, || {
let input = "${GROK_HOOKS_ENV_EXPAND_MODIFIER_UNSET:-/default/path.sh}";
let out = expand_env_vars_with_extra(input, &extra);
assert_eq!(out, input);
});
}
/// Even when the var IS set, the modifier form must be preserved
/// verbatim -- the shell's `:-` semantics differ from shellexpand's
/// (notably for set-but-empty values), so deferring the entire form
/// to the runtime `sh -c` branch is the only safe choice.
#[test]
fn preserves_default_modifier_when_var_set() {
let mut extra = HashMap::new();
extra.insert(
"GROK_HOOKS_DEFAULT_SET".to_string(),
"/from/extra".to_string(),
);
let input = "${GROK_HOOKS_DEFAULT_SET:-/fallback}";
let out = expand_env_vars_with_extra(input, &extra);
assert_eq!(out, input);
}
/// `${VAR-default}` (no colon) — also a modifier form.
#[test]
fn preserves_no_colon_default_modifier() {
let extra = HashMap::new();
let input = "${GROK_HOOKS_NCD-/fallback}";
let out = expand_env_vars_with_extra(input, &extra);
assert_eq!(out, input);
}
/// `${VAR:=x}` — assignment modifier.
#[test]
fn preserves_assignment_modifier() {
let extra = HashMap::new();
let input = "${GROK_HOOKS_ASSIGN:=/assigned/path.sh}";
let out = expand_env_vars_with_extra(input, &extra);
assert_eq!(out, input);
}
/// `${VAR:?msg}` — error modifier.
#[test]
fn preserves_error_modifier() {
let extra = HashMap::new();
let input = "${GROK_HOOKS_ERR:?error message}";
let out = expand_env_vars_with_extra(input, &extra);
assert_eq!(out, input);
}
/// `${VAR:+x}` — alternate-value modifier.
#[test]
fn preserves_alternate_modifier() {
let extra = HashMap::new();
let input = "${GROK_HOOKS_ALT:+/used/if/set}";
let out = expand_env_vars_with_extra(input, &extra);
assert_eq!(out, input);
}
/// `${VAR%pat}` — suffix-strip modifier.
#[test]
fn preserves_suffix_strip_modifier() {
let extra = HashMap::new();
let input = "${GROK_HOOKS_SUFFIX%.sh}";
let out = expand_env_vars_with_extra(input, &extra);
assert_eq!(out, input);
}
/// `${VAR#pat}` — prefix-strip modifier.
#[test]
fn preserves_prefix_strip_modifier() {
let extra = HashMap::new();
let input = "${GROK_HOOKS_PREFIX#prefix/}";
let out = expand_env_vars_with_extra(input, &extra);
assert_eq!(out, input);
}
/// `${VAR/foo/bar}` — pattern-substitution modifier.
#[test]
fn preserves_substitution_modifier() {
let extra = HashMap::new();
let input = "${GROK_HOOKS_SUB/foo/bar}";
let out = expand_env_vars_with_extra(input, &extra);
assert_eq!(out, input);
}
/// `${VAR:N:M}` — substring modifier.
#[test]
fn preserves_substring_modifier() {
let extra = HashMap::new();
let input = "${GROK_HOOKS_SUBSTR:0:5}";
let out = expand_env_vars_with_extra(input, &extra);
assert_eq!(out, input);
}
/// Mixed: a modifier-form sits next to a plain form; only the plain
/// one is expanded.
#[test]
fn mixed_plain_and_modifier_only_plain_expanded() {
let mut extra = HashMap::new();
extra.insert("GROK_HOOKS_PLAIN".to_string(), "/usr/local".to_string());
let input = "${GROK_HOOKS_PLAIN}/${GROK_HOOKS_DEFER:-/fallback}";
let out = expand_env_vars_with_extra(input, &extra);
assert_eq!(out, "/usr/local/${GROK_HOOKS_DEFER:-/fallback}");
}
// ── Set-but-empty regression test ────────────────────────────
/// When the var is set in `extra` but to the empty string, the
/// no-modifier form `${VAR}` resolves to "" (matching shellexpand's
/// behaviour and what users typically expect).
#[test]
fn empty_extra_value_resolves_to_empty_for_plain_form() {
let mut extra = HashMap::new();
extra.insert("GROK_HOOKS_EMPTY".to_string(), "".to_string());
let out = expand_env_vars_with_extra("[${GROK_HOOKS_EMPTY}]", &extra);
assert_eq!(out, "[]");
}
/// When the var is set in `extra` but to the empty string, the
/// modifier-form `${VAR:-default}` is preserved verbatim (so that
/// the runtime `sh -c` branch can apply POSIX `:-` semantics, which
/// differ from shellexpand's: bash returns the default for empty
/// values, shellexpand returns the empty string). This documents
/// that the load-time pass does NOT trigger the modifier branch.
#[test]
fn empty_extra_value_does_not_trigger_default() {
let mut extra = HashMap::new();
extra.insert("GROK_HOOKS_EMPTY_MOD".to_string(), "".to_string());
let input = "${GROK_HOOKS_EMPTY_MOD:-/fallback}";
let out = expand_env_vars_with_extra(input, &extra);
assert_eq!(out, input);
}
// ── Single-pass expansion (no recursion) ────────────────────
/// A value in `extra` that itself contains a `$VAR` reference must
/// NOT be re-expanded. Recursion would be a DoS vector and a
/// semantic surprise. shellexpand's
/// `env_with_context_no_errors` is single-pass by design; this
/// test locks the property in.
#[test]
fn extra_values_are_not_recursively_expanded() {
with_env_var(
"GROK_HOOKS_RECURSION_BAR",
Some("should-not-appear"),
|| {
let mut extra = HashMap::new();
extra.insert(
"GROK_HOOKS_RECURSION_FOO".to_string(),
"$GROK_HOOKS_RECURSION_BAR".to_string(),
);
let out = expand_env_vars_with_extra("${GROK_HOOKS_RECURSION_FOO}", &extra);
assert_eq!(out, "$GROK_HOOKS_RECURSION_BAR");
},
);
}
// ── mask_modifier_forms helper unit tests ────────────────────
/// A fixed test-only sentinel used to make the masked-output
/// assertions deterministic. Production code uses [`make_sentinel`]
/// which returns a per-call randomized value (see the sentinel
/// collision regression test below that exercises the random
/// path end-to-end).
const TEST_SENTINEL: &str = "<<TEST_SENTINEL>>";
#[test]
fn mask_helper_passes_plain_form_through() {
assert_eq!(mask_modifier_forms("${PLAIN}", TEST_SENTINEL), "${PLAIN}");
}
#[test]
fn mask_helper_masks_default_form() {
// Lock down the exact masked output, not
// just the sentinel-contains predicate.
let masked = mask_modifier_forms("${VAR:-x}", TEST_SENTINEL);
assert_eq!(masked, format!("{TEST_SENTINEL}VAR:-x}}"));
}
#[test]
fn mask_helper_handles_unterminated_brace() {
// No closing brace -- no masking, emit verbatim.
assert_eq!(
mask_modifier_forms("${VAR:-no-close", TEST_SENTINEL),
"${VAR:-no-close"
);
}
#[test]
fn mask_helper_passes_bare_form_through() {
assert_eq!(mask_modifier_forms("$BARE_VAR", TEST_SENTINEL), "$BARE_VAR");
}
#[test]
fn mask_helper_handles_multibyte_chars() {
// Full-equality assertion locks down the
// exact bytes, including UTF-8 boundary placement.
let input = "h\u{e9}llo${PLAIN}w\u{f6}rld${VAR:-x}";
let masked = mask_modifier_forms(input, TEST_SENTINEL);
let expected = format!("h\u{e9}llo${{PLAIN}}w\u{f6}rld{TEST_SENTINEL}VAR:-x}}");
assert_eq!(masked, expected);
}
// ── Nested / interleaved edge cases ─────────────────────────
/// Two consecutive modifier forms with no
/// intervening text. Both must be masked independently.
#[test]
fn mask_helper_consecutive_modifier_forms() {
let masked = mask_modifier_forms("${A:-x}${B:-y}", TEST_SENTINEL);
assert_eq!(
masked,
format!("{TEST_SENTINEL}A:-x}}{TEST_SENTINEL}B:-y}}")
);
}
/// Nested braces inside a modifier body. The
/// custom byte-walker matches the FIRST closing `}`, so the
/// inner `${B}` is NOT a separately-recognised plain form -- it
/// becomes part of the outer modifier body and is masked along
/// with the outer form. The literal `${B}` is preserved inside
/// the masked body, ready for the runtime `sh -c` branch (which
/// handles nesting natively).
///
/// The trailing extra `}` is left as-is (it has no matching `${`).
/// This documented behaviour is intentional: complex nested
/// expansions are an explicit deferral to runtime.
#[test]
fn mask_helper_nested_braces_in_modifier_body() {
let masked = mask_modifier_forms("${A:-${B}}", TEST_SENTINEL);
// First `}` closes the outer modifier match; `${B}` is INSIDE
// the masked body. The tail `}` is a stray brace, preserved
// as-is.
assert_eq!(masked, format!("{TEST_SENTINEL}A:-${{B}}}}"));
}
/// A closed plain form followed by an
/// unterminated modifier form. The plain form passes through;
/// the unterminated tail is emitted verbatim because the walker
/// requires a closing `}` to consider a `${...}` substring a
/// real form.
#[test]
fn mask_helper_closed_then_unterminated() {
let masked = mask_modifier_forms("${A}${B:-", TEST_SENTINEL);
assert_eq!(masked, "${A}${B:-");
}
// ── Sentinel collision regression ──────────────────────────
/// The previous sentinel was `\x00\x00`. If a
/// future change reverted to that sentinel, an `extra_env` value
/// or input string containing the same byte sequence would be
/// silently rewritten to `${`. The new sentinel is a long magic
/// ASCII string sandwiched between two PUA characters --
/// vanishingly unlikely to collide. This regression test
/// constructs an input containing the OLD `\x00\x00` sequence
/// AND a value containing the OLD sequence in `extra_env`, and
/// asserts both pass through unchanged.
#[test]
fn mask_helper_preserves_pre_existing_old_nul_sentinel() {
// The OLD sentinel as a literal in the input.
let input = "prefix\u{0}\u{0}suffix";
assert_eq!(mask_modifier_forms(input, TEST_SENTINEL), input);
}
/// Companion to the above: an `extra_env` value containing the
/// OLD sentinel must not be rewritten to `${...}` after expansion.
#[test]
fn expand_preserves_pre_existing_old_nul_sentinel_in_extra() {
let mut extra = HashMap::new();
// Value contains the legacy 2-NUL sentinel followed by what
// would have been parsed as an identifier+brace.
extra.insert("VAL".to_string(), "\u{0}\u{0}OLD}".to_string());
let out = expand_env_vars_with_extra("prefix${VAL}suffix", &extra);
// Output must contain the literal NUL bytes verbatim, NOT
// `${OLD}`.
assert_eq!(out, "prefix\u{0}\u{0}OLD}suffix");
assert!(
!out.contains("${OLD}"),
"legacy sentinel must NOT trigger an unmask-to-`${{`, got {out:?}"
);
}
/// An earlier sentinel was a fixed string
/// `"\u{f8ff}__GROK_HOOKS_MASK__\u{f8ff}"`. A user-supplied
/// `extra_env` value containing that exact byte sequence would
/// have been silently rewritten to `${` by the unmask step. The
/// per-call randomized sentinel removes this hazard. This
/// regression test asserts the legacy fixed sentinel passes
/// through verbatim when it appears in an extra-env value, even
/// though the input also references that variable through `${VAL}`.
#[test]
fn expand_preserves_pre_existing_legacy_fixed_sentinel_in_extra() {
let legacy_sentinel = "\u{f8ff}__GROK_HOOKS_MASK__\u{f8ff}";
let mut extra = HashMap::new();
// Value embeds the legacy sentinel followed by what would
// have been parsed as an identifier+brace if the unmask
// sentinel-replace had collided.
extra.insert(
"VAL".to_string(),
format!("payload-{legacy_sentinel}OLD}}-tail"),
);
// Reference VAL via a plain form so its value gets spliced
// into the output.
let out = expand_env_vars_with_extra("prefix${VAL}suffix", &extra);
// The legacy sentinel substring must appear in the output
// verbatim -- it must NOT be rewritten to `${`.
assert_eq!(
out,
format!("prefixpayload-{legacy_sentinel}OLD}}-tailsuffix")
);
assert!(
!out.contains("${OLD}"),
"legacy fixed sentinel must NOT trigger an unmask-to-`${{`, got {out:?}"
);
}
/// Companion: arbitrary high-entropy bytes in an extra-env value
/// must also pass through verbatim. (Sanity check that the
/// per-call sentinel doesn't collide with random binary content.)
#[test]
fn expand_preserves_arbitrary_bytes_in_extra() {
let mut extra = HashMap::new();
// A mix of printable ASCII, NULs, PUA chars, brace bytes, and
// dollar signs -- the kinds of bytes most likely to clash
// with any future sentinel scheme.
let exotic = "\u{0}\u{f8ff}${weird}}\u{f8ff}\u{0}__MASK__";
extra.insert("VAL".to_string(), exotic.to_string());
let out = expand_env_vars_with_extra("X=${VAL}", &extra);
assert_eq!(out, format!("X={exotic}"));
}
// ── iter_env_var_references unit tests ───────────────────────
/// Lock down the iterator output for a single braced plain form.
#[test]
fn iter_yields_plain_braced_form() {
let refs: Vec<_> = iter_env_var_references("foo ${BAR} baz").collect();
assert_eq!(refs.len(), 1);
assert_eq!(refs[0].name, "BAR");
assert!(refs[0].braced);
assert!(!refs[0].has_modifier);
assert_eq!(refs[0].start, 4);
assert_eq!(refs[0].end, 10);
}
/// Lock down the iterator output for a single bare form.
#[test]
fn iter_yields_bare_form() {
let refs: Vec<_> = iter_env_var_references("foo $BAR baz").collect();
assert_eq!(refs.len(), 1);
assert_eq!(refs[0].name, "BAR");
assert!(!refs[0].braced);
assert!(!refs[0].has_modifier);
assert_eq!(refs[0].start, 4);
assert_eq!(refs[0].end, 8);
}
/// Modifier form sets has_modifier = true.
#[test]
fn iter_flags_modifier_form() {
let refs: Vec<_> = iter_env_var_references("${VAR:-x}").collect();
assert_eq!(refs.len(), 1);
assert_eq!(refs[0].name, "VAR");
assert!(refs[0].braced);
assert!(refs[0].has_modifier);
assert_eq!(refs[0].start, 0);
assert_eq!(refs[0].end, 9);
}
/// Shell positionals / specials / command substitutions are NOT
/// yielded.
#[test]
fn iter_skips_shell_specials() {
let refs: Vec<_> = iter_env_var_references("$1 $$ $? $# $(date) $@").collect();
assert!(
refs.is_empty(),
"shell special params must not yield refs, got {refs:?}"
);
}
/// Unterminated braced form: the `$` is consumed; nothing yielded.
#[test]
fn iter_skips_unterminated_brace() {
let refs: Vec<_> = iter_env_var_references("${VAR:-no-close").collect();
assert!(refs.is_empty(), "unterminated brace must yield no refs");
}
/// Empty / invalid identifier inside braces: yielded with empty
/// name and has_modifier=false.
#[test]
fn iter_yields_invalid_braced_form_with_empty_name() {
let refs: Vec<_> = iter_env_var_references("${:-foo}").collect();
assert_eq!(refs.len(), 1);
assert_eq!(refs[0].name, "");
assert!(refs[0].braced);
assert!(
!refs[0].has_modifier,
"invalid form (no identifier) must not be flagged as a modifier form"
);
}
/// Mixed input: plain, modifier, bare, and a positional.
#[test]
fn iter_yields_mixed_forms_in_order() {
let refs: Vec<_> = iter_env_var_references("${A}${B:-x}$C $1").collect();
assert_eq!(refs.len(), 3);
assert_eq!(refs[0].name, "A");
assert!(refs[0].braced && !refs[0].has_modifier);
assert_eq!(refs[1].name, "B");
assert!(refs[1].braced && refs[1].has_modifier);
assert_eq!(refs[2].name, "C");
assert!(!refs[2].braced && !refs[2].has_modifier);
}
/// Nested braces are matched at the FIRST `}` (legacy parser
/// behaviour, see `mask_helper_nested_braces_in_modifier_body`).
#[test]
fn iter_matches_first_closing_brace_for_nested() {
// Bytes: `${A:-${B}}` (indices 0..10).
// The outer ref begins at the leading `$` (0), reads `A` as
// the identifier, sees `:` as the first non-identifier byte,
// then walks forward to the FIRST `}` -- which is the closing
// brace of the inner `${B}` at index 8. So end = 9. The
// trailing `}` at index 9 is literal text.
let refs: Vec<_> = iter_env_var_references("${A:-${B}}").collect();
assert_eq!(refs.len(), 1);
assert_eq!(refs[0].name, "A");
assert!(refs[0].braced);
assert!(refs[0].has_modifier);
assert_eq!(refs[0].start, 0);
assert_eq!(refs[0].end, 9);
}
}

View file

@ -0,0 +1,59 @@
use std::path::PathBuf;
/// Errors that can occur during hook loading, parsing, or execution.
#[derive(Debug, thiserror::Error)]
pub enum HookError {
#[error("failed to read hook file {path}: {source}")]
ReadFile {
path: PathBuf,
source: std::io::Error,
},
#[error("failed to parse hook file {path}: {detail}")]
ParseFile { path: PathBuf, detail: String },
#[error("hook {name} in {path}: invalid regex pattern: {source}")]
InvalidMatcher {
name: String,
path: PathBuf,
source: regex::Error,
},
#[error("hook {name} in {path}: lifecycle hooks ({event}) must not specify a matcher in v0")]
LifecycleMatcherNotAllowed {
name: String,
path: PathBuf,
event: String,
},
#[error("hook {name} timed out after {elapsed_ms}ms")]
Timeout { name: String, elapsed_ms: u64 },
#[error("hook {name} command failed: {source}")]
CommandFailed {
name: String,
source: std::io::Error,
},
#[error("hook {name} produced invalid output: {detail}")]
InvalidOutput { name: String, detail: String },
#[error("hook {name}: command not found or not executable: {path}")]
CommandNotFound { name: String, path: PathBuf },
#[error("hook {name} in {path}: {detail}")]
InvalidConfig {
name: String,
path: PathBuf,
detail: String,
},
#[error(
"hook {name} in {path}: unsupported handler type '{handler_type}', only 'command' is supported in v0"
)]
UnsupportedHandlerType {
name: String,
path: PathBuf,
handler_type: String,
},
}

View file

@ -0,0 +1,545 @@
use serde::Serialize;
/// Maximum serialized size for `toolInput` or `toolResult` in bytes (128 KB).
pub const MAX_PAYLOAD_SIZE: usize = 128 * 1024;
/// Hook event types.
///
/// Accepts both PascalCase (`"PreToolUse"`) and snake_case (`"pre_tool_use"`)
/// during deserialization for migration compatibility.
/// Serializes to snake_case for the hook envelope wire format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum HookEventName {
// ── Session lifecycle ───────────────────────────────────────
SessionStart,
SessionEnd,
/// Fires when an agent turn ends (completed, cancelled, or error).
Stop,
/// Fires when the turn ends due to an API error. Output and exit code are ignored.
StopFailure,
// ── Tool events ─────────────────────────────────────────────
PreToolUse,
PostToolUse,
/// Fires after a tool call fails (throws an error).
PostToolUseFailure,
/// Fires when a tool call is denied by the permission system.
PermissionDenied,
// ── User / notification events ──────────────────────────────
/// Fires when the user submits a prompt.
UserPromptSubmit,
/// Fires when a notification is sent (e.g., permission prompt, idle).
Notification,
// ── Subagent events ─────────────────────────────────────────
/// Fires when a subagent is spawned.
SubagentStart,
/// Fires when a subagent completes.
SubagentStop,
/// Alias for SubagentStop (kept for backward compatibility).
SubagentEnd,
// ── Compaction events ───────────────────────────────────────
/// Fires before context compaction.
PreCompact,
/// Fires after context compaction completes.
PostCompact,
}
impl<'de> serde::Deserialize<'de> for HookEventName {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
match s.as_str() {
// PascalCase (native) + snake_case + camelCase (third-party compat).
// Per-operation hook names (beforeShellExecution, afterFileEdit, etc.)
// map to our generic PreToolUse/PostToolUse — the hook script receives the
// tool name in JSON input and can filter, or use the `matcher` field.
"SessionStart" | "session_start" | "sessionStart" => Ok(Self::SessionStart),
"PreToolUse"
| "pre_tool_use"
| "preToolUse"
| "beforeShellExecution"
| "beforeMCPExecution"
| "beforeReadFile" => Ok(Self::PreToolUse),
"PostToolUse"
| "post_tool_use"
| "postToolUse"
| "afterShellExecution"
| "afterMCPExecution"
| "afterFileEdit"
| "afterAgentResponse"
| "afterAgentThought" => Ok(Self::PostToolUse),
"PostToolUseFailure" | "post_tool_use_failure" | "postToolUseFailure" => {
Ok(Self::PostToolUseFailure)
}
"SessionEnd" | "session_end" | "sessionEnd" => Ok(Self::SessionEnd),
"Stop" | "stop" => Ok(Self::Stop),
"StopFailure" | "stop_failure" | "stopFailure" => Ok(Self::StopFailure),
"Notification" | "notification" => Ok(Self::Notification),
"UserPromptSubmit" | "user_prompt_submit" | "beforeSubmitPrompt" => {
Ok(Self::UserPromptSubmit)
}
"PermissionDenied" | "permission_denied" | "permissionDenied" => {
Ok(Self::PermissionDenied)
}
"SubagentStart" | "subagent_start" | "subagentStart" => Ok(Self::SubagentStart),
"SubagentStop" | "subagent_stop" | "subagentStop" => Ok(Self::SubagentStop),
"SubagentEnd" | "subagent_end" | "subagentEnd" => Ok(Self::SubagentEnd),
"PreCompact" | "pre_compact" | "preCompact" => Ok(Self::PreCompact),
"PostCompact" | "post_compact" | "postCompact" => Ok(Self::PostCompact),
other => Err(serde::de::Error::custom(format!(
"unknown hook event: '{other}'. Expected one of: \
SessionStart, PreToolUse, PostToolUse, PostToolUseFailure, \
SessionEnd, Stop, StopFailure, Notification, UserPromptSubmit, \
PermissionDenied, SubagentStart, SubagentStop, \
PreCompact, PostCompact"
))),
}
}
}
impl std::fmt::Display for HookEventName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::SessionStart => write!(f, "session_start"),
Self::PreToolUse => write!(f, "pre_tool_use"),
Self::PostToolUse => write!(f, "post_tool_use"),
Self::PostToolUseFailure => write!(f, "post_tool_use_failure"),
Self::SessionEnd => write!(f, "session_end"),
Self::Stop => write!(f, "stop"),
Self::StopFailure => write!(f, "stop_failure"),
Self::Notification => write!(f, "notification"),
Self::UserPromptSubmit => write!(f, "user_prompt_submit"),
Self::PermissionDenied => write!(f, "permission_denied"),
Self::SubagentStart => write!(f, "subagent_start"),
Self::SubagentStop | Self::SubagentEnd => write!(f, "subagent_stop"),
Self::PreCompact => write!(f, "pre_compact"),
Self::PostCompact => write!(f, "post_compact"),
}
}
}
impl HookEventName {
/// Collapse alias variants to their canonical form so a registration and the fired
/// event meet on one key regardless of which spelling each used (`SubagentEnd` is an
/// alias of `SubagentStop`).
pub fn canonical(self) -> Self {
match self {
Self::SubagentEnd => Self::SubagentStop,
other => other,
}
}
/// Returns true if this event type uses blocking (deny/allow) semantics.
pub fn is_blocking(&self) -> bool {
matches!(self, Self::PreToolUse)
}
/// Events that don't support matcher patterns (fire on every occurrence).
pub fn is_lifecycle(&self) -> bool {
matches!(
self,
Self::SessionStart | Self::SessionEnd | Self::Stop | Self::UserPromptSubmit
)
}
}
/// The normalized event envelope sent to hook commands on stdin as JSON.
///
/// Contains common metadata plus an event-specific payload.
/// All field names use camelCase for the JSON wire format.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HookEventEnvelope {
pub hook_event_name: HookEventName,
pub session_id: String,
pub cwd: String,
pub workspace_root: String,
pub timestamp: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub transcript_path: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_identifier: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub prompt_id: Option<String>,
#[serde(flatten)]
pub payload: HookPayload,
}
/// Event-specific payload variants, flattened into the envelope JSON via
/// `#[serde(untagged)]`. Grouped to match `HookEventName`.
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum HookPayload {
// ── Session lifecycle ───────────────────────────────────────
SessionStart {
source: String,
#[serde(rename = "modelId", skip_serializing_if = "Option::is_none")]
model_id: Option<String>,
#[serde(rename = "agentType", skip_serializing_if = "Option::is_none")]
agent_type: Option<String>,
},
SessionEnd {
reason: String,
#[serde(rename = "turnCount", skip_serializing_if = "Option::is_none")]
turn_count: Option<u64>,
#[serde(rename = "toolCallCount", skip_serializing_if = "Option::is_none")]
tool_call_count: Option<u64>,
},
Stop {
reason: String,
},
StopFailure {
error: String,
},
// ── Tool events ─────────────────────────────────────────────
PreToolUse {
/// The tool the model invoked. For the meta-dispatch tools (`use_tool`
/// and the external MCP-call tool) this is the resolved underlying tool
/// (`server__tool`), not the dispatcher — matchers key on it directly.
#[serde(rename = "toolName")]
tool_name: String,
#[serde(rename = "toolUseId")]
tool_use_id: String,
#[serde(rename = "toolInput")]
tool_input: serde_json::Value,
#[serde(rename = "toolInputTruncated")]
tool_input_truncated: bool,
#[serde(rename = "permissionMode", skip_serializing_if = "Option::is_none")]
permission_mode: Option<String>,
/// The subagent's type when this tool runs inside one (the envelope's `sessionId`
/// gives its identity); `None` for the top-level session.
#[serde(rename = "subagentType", skip_serializing_if = "Option::is_none")]
subagent_type: Option<String>,
},
PostToolUse {
/// Resolved underlying tool for meta-dispatch tools (see `PreToolUse`).
#[serde(rename = "toolName")]
tool_name: String,
#[serde(rename = "toolUseId")]
tool_use_id: String,
#[serde(rename = "toolInput")]
tool_input: serde_json::Value,
#[serde(rename = "toolResult")]
tool_result: serde_json::Value,
#[serde(rename = "toolInputTruncated")]
tool_input_truncated: bool,
#[serde(rename = "toolResultTruncated")]
tool_result_truncated: bool,
#[serde(rename = "durationMs", skip_serializing_if = "Option::is_none")]
duration_ms: Option<u64>,
#[serde(rename = "isBackgrounded")]
is_backgrounded: bool,
#[serde(rename = "subagentType", skip_serializing_if = "Option::is_none")]
subagent_type: Option<String>,
},
PostToolUseFailure {
/// Resolved underlying tool for meta-dispatch tools (see `PreToolUse`).
#[serde(rename = "toolName")]
tool_name: String,
#[serde(rename = "toolUseId")]
tool_use_id: String,
#[serde(rename = "toolInput")]
tool_input: serde_json::Value,
#[serde(rename = "toolInputTruncated")]
tool_input_truncated: bool,
error: String,
#[serde(rename = "subagentType", skip_serializing_if = "Option::is_none")]
subagent_type: Option<String>,
},
PermissionDenied {
/// Resolved underlying tool for meta-dispatch tools (see `PreToolUse`).
#[serde(rename = "toolName")]
tool_name: String,
#[serde(rename = "toolUseId")]
tool_use_id: String,
#[serde(rename = "toolInput")]
tool_input: serde_json::Value,
#[serde(rename = "toolInputTruncated")]
tool_input_truncated: bool,
},
// ── User / notification events ──────────────────────────────
/// Fires when the user submits a prompt.
UserPromptSubmit {
#[serde(skip_serializing_if = "Option::is_none")]
prompt: Option<String>,
},
/// Fires on agent notifications (permission prompts, idle, etc.).
Notification {
#[serde(rename = "notificationType")]
notification_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
message: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
title: Option<String>,
/// Compat: some callers use `level` instead of `notificationType`.
#[serde(skip_serializing_if = "Option::is_none")]
level: Option<String>,
},
// ── Subagent events ─────────────────────────────────────────
/// Fires when a subagent is spawned.
SubagentStart {
#[serde(rename = "subagentId")]
subagent_id: String,
#[serde(rename = "subagentType")]
subagent_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
description: Option<String>,
},
/// Fires when a subagent completes.
SubagentStop {
#[serde(rename = "subagentId")]
subagent_id: String,
#[serde(rename = "subagentType")]
subagent_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
description: Option<String>,
#[serde(rename = "exitCode", skip_serializing_if = "Option::is_none")]
exit_code: Option<i32>,
#[serde(rename = "durationMs", skip_serializing_if = "Option::is_none")]
duration_ms: Option<u64>,
},
// ── Compaction events ───────────────────────────────────────
PreCompact {
/// "manual" or "auto".
source: String,
},
PostCompact {
/// "manual" or "auto".
source: String,
},
}
/// Truncate a JSON value if its serialized size exceeds `MAX_PAYLOAD_SIZE`.
///
/// Returns `(possibly_truncated_value, was_truncated)`.
pub fn truncate_payload(value: serde_json::Value) -> (serde_json::Value, bool) {
let serialized = serde_json::to_string(&value).unwrap_or_default();
if serialized.len() <= MAX_PAYLOAD_SIZE {
return (value, false);
}
// Cut at the largest char boundary <= MAX_PAYLOAD_SIZE so the slice never
// splits a multibyte codepoint.
let mut end = MAX_PAYLOAD_SIZE;
while !serialized.is_char_boundary(end) {
end -= 1;
}
let mut result = serialized[..end].to_string();
result.push_str(" [truncated]");
(serde_json::Value::String(result), true)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn event_name_deser_all_variants() {
let cases: &[(&str, &str, HookEventName)] = &[
("SessionStart", "session_start", HookEventName::SessionStart),
("PreToolUse", "pre_tool_use", HookEventName::PreToolUse),
("PostToolUse", "post_tool_use", HookEventName::PostToolUse),
(
"PostToolUseFailure",
"post_tool_use_failure",
HookEventName::PostToolUseFailure,
),
("SessionEnd", "session_end", HookEventName::SessionEnd),
("Stop", "stop", HookEventName::Stop),
("StopFailure", "stop_failure", HookEventName::StopFailure),
("Notification", "notification", HookEventName::Notification),
(
"UserPromptSubmit",
"user_prompt_submit",
HookEventName::UserPromptSubmit,
),
(
"PermissionDenied",
"permission_denied",
HookEventName::PermissionDenied,
),
(
"SubagentStart",
"subagent_start",
HookEventName::SubagentStart,
),
("SubagentStop", "subagent_stop", HookEventName::SubagentStop),
("SubagentEnd", "subagent_end", HookEventName::SubagentEnd),
("PreCompact", "pre_compact", HookEventName::PreCompact),
("PostCompact", "post_compact", HookEventName::PostCompact),
];
for (pascal, snake, expected) in cases {
let from_pascal: HookEventName =
serde_json::from_str(&format!("\"{pascal}\"")).unwrap();
assert_eq!(
from_pascal, *expected,
"PascalCase deser failed for {pascal}"
);
let from_snake: HookEventName = serde_json::from_str(&format!("\"{snake}\"")).unwrap();
assert_eq!(from_snake, *expected, "snake_case deser failed for {snake}");
}
}
#[test]
fn event_name_display_all_variants() {
let cases: &[(HookEventName, &str)] = &[
(HookEventName::SessionStart, "session_start"),
(HookEventName::PreToolUse, "pre_tool_use"),
(HookEventName::PostToolUse, "post_tool_use"),
(HookEventName::PostToolUseFailure, "post_tool_use_failure"),
(HookEventName::SessionEnd, "session_end"),
(HookEventName::Stop, "stop"),
(HookEventName::StopFailure, "stop_failure"),
(HookEventName::Notification, "notification"),
(HookEventName::UserPromptSubmit, "user_prompt_submit"),
(HookEventName::PermissionDenied, "permission_denied"),
(HookEventName::SubagentStart, "subagent_start"),
(HookEventName::SubagentStop, "subagent_stop"),
(HookEventName::SubagentEnd, "subagent_stop"), // alias collapses
(HookEventName::PreCompact, "pre_compact"),
(HookEventName::PostCompact, "post_compact"),
];
for (event, expected) in cases {
assert_eq!(&event.to_string(), expected, "Display wrong for {event:?}");
}
}
#[test]
fn event_name_serde_roundtrip() {
let name = HookEventName::PreToolUse;
let json = serde_json::to_string(&name).unwrap();
assert_eq!(json, "\"pre_tool_use\"");
let parsed: HookEventName = serde_json::from_str(&json).unwrap();
assert_eq!(parsed, name);
}
#[test]
fn event_name_unknown_rejected() {
let result = serde_json::from_str::<HookEventName>("\"UnknownEvent\"");
assert!(result.is_err());
}
#[test]
fn event_name_is_blocking() {
assert!(HookEventName::PreToolUse.is_blocking());
for event in [
HookEventName::SessionStart,
HookEventName::PostToolUse,
HookEventName::PostToolUseFailure,
HookEventName::SessionEnd,
HookEventName::Stop,
HookEventName::StopFailure,
HookEventName::Notification,
HookEventName::UserPromptSubmit,
HookEventName::PermissionDenied,
HookEventName::SubagentStart,
HookEventName::SubagentStop,
HookEventName::SubagentEnd,
HookEventName::PreCompact,
HookEventName::PostCompact,
] {
assert!(!event.is_blocking(), "{event:?} should not be blocking");
}
}
#[test]
fn event_name_is_lifecycle() {
let lifecycle = [
HookEventName::SessionStart,
HookEventName::SessionEnd,
HookEventName::Stop,
HookEventName::UserPromptSubmit,
];
for event in lifecycle {
assert!(event.is_lifecycle(), "{event:?} should be lifecycle");
}
let matchable = [
HookEventName::PreToolUse,
HookEventName::PostToolUse,
HookEventName::PostToolUseFailure,
HookEventName::PermissionDenied,
HookEventName::StopFailure,
HookEventName::Notification,
HookEventName::SubagentStart,
HookEventName::SubagentStop,
HookEventName::SubagentEnd,
HookEventName::PreCompact,
HookEventName::PostCompact,
];
for event in matchable {
assert!(
!event.is_lifecycle(),
"{event:?} should support matchers, not be lifecycle"
);
}
}
#[test]
fn truncate_small_payload() {
let value = serde_json::json!({"key": "small"});
let (result, truncated) = truncate_payload(value.clone());
assert!(!truncated);
assert_eq!(result, value);
}
#[test]
fn truncate_large_payload() {
let big_string = "x".repeat(MAX_PAYLOAD_SIZE + 1000);
let value = serde_json::Value::String(big_string);
let (result, truncated) = truncate_payload(value);
assert!(truncated);
let s = result.as_str().unwrap();
assert!(s.ends_with("[truncated]"));
// Serialized size of the result string value should be <= MAX_PAYLOAD_SIZE + overhead
assert!(s.len() < MAX_PAYLOAD_SIZE + 100);
}
#[test]
fn truncate_large_payload_cuts_on_char_boundary() {
// '€' is 3 bytes, so the MAX_PAYLOAD_SIZE-th byte lands mid-codepoint.
let value = serde_json::Value::String("".repeat(MAX_PAYLOAD_SIZE));
let (result, truncated) = truncate_payload(value);
assert!(truncated);
assert!(result.as_str().unwrap().ends_with("[truncated]"));
}
#[test]
fn envelope_serializes_camel_case() {
let envelope = HookEventEnvelope {
hook_event_name: HookEventName::SessionStart,
session_id: "test-session".into(),
cwd: "/tmp".into(),
workspace_root: "/tmp".into(),
timestamp: "2025-01-01T00:00:00Z".into(),
transcript_path: None,
client_identifier: None,
prompt_id: None,
payload: HookPayload::SessionStart {
source: "new".into(),
model_id: Some("grok-3".into()),
agent_type: None,
},
};
let json = serde_json::to_string(&envelope).unwrap();
assert!(json.contains("hookEventName"));
assert!(json.contains("sessionId"));
assert!(json.contains("workspaceRoot"));
assert!(json.contains("modelId"));
// Should NOT contain snake_case versions
assert!(!json.contains("hook_event_name"));
assert!(!json.contains("session_id"));
}
}

View file

@ -0,0 +1,50 @@
//! # xai-grok-hooks
//!
//! Runtime hook system for Grok — file-based discovery, command execution,
//! and policy enforcement.
//!
//! ## Overview
//!
//! This crate provides a minimal hooks system for Grok. Hooks are discovered
//! from dedicated directories (`~/.grok/hooks/` and `<git-worktree-root>/.grok/hooks/`),
//! defined in JSON files (compatible settings format), and executed as child processes.
//!
//! ## v0 scope
//!
//! - Four event types: `session_start`, `pre_tool_use`, `post_tool_use`, `session_end`
//! - Command-backed hooks only
//! - `pre_tool_use` hooks can deny/allow (blocking); all others are non-blocking
//! - Fail-open by default: hook failures do not block normal operation
//!
//! ## Quick start
//!
//! ```rust,no_run
//! use std::path::Path;
//! use xai_grok_hooks::discovery::load_hooks;
//! use xai_grok_hooks::event::HookEventName;
//!
//! let (registry, errors) = load_hooks(
//! Some(Path::new("/home/user/.grok/hooks")),
//! Some(Path::new("/project/.grok/hooks")),
//! );
//!
//! for err in &errors {
//! eprintln!("hook load warning: {err}");
//! }
//!
//! let pre_hooks = registry.hooks_for(HookEventName::PreToolUse);
//! println!("loaded {} pre_tool_use hooks", pre_hooks.len());
//! ```
pub mod config;
pub mod discovery;
pub mod dispatcher;
mod env_expand;
pub mod error;
pub mod event;
pub mod matcher;
pub mod result;
pub mod runner;
#[cfg(test)]
mod test_support;
pub mod trust;

View file

@ -0,0 +1,196 @@
use regex::Regex;
use xai_grok_tools::types::{claude_names_for, grok_names_for};
/// A compiled hook matcher for tool names. The pattern semantics are chosen so that
/// `matcher` entries in hooks migrated from other agent CLIs keep firing unchanged:
///
/// - an empty pattern or `"*"` matches every tool;
/// - a "simple" pattern (only `[A-Za-z0-9_|]`, i.e. a plain name or `|`-list) is an
/// **exact** match against each name (after external→Grok alias expansion), NOT a regex;
/// - anything else is an **unanchored** regex (also tested against the tool's external
/// alias names, so e.g. `^Bash$` matches the Grok tool `run_terminal_command`).
///
/// The simple-vs-regex split is deliberate: it avoids anchoring a `|`-alternation (a
/// naive `^a|b|c$` anchors only the first/last term and silently over-matches). Whitespace
/// is significant (not trimmed): `" "` is a regex that matches nothing.
#[derive(Debug, Clone)]
pub struct HookMatcher {
kind: MatcherKind,
}
#[derive(Debug, Clone)]
enum MatcherKind {
All,
Exact(Vec<String>),
Regex(Regex),
}
impl HookMatcher {
/// Compile a matcher from a user pattern. Errors only when a regex-form pattern is
/// itself invalid regex (simple/empty/`*` forms never error).
pub fn new(pattern: &str) -> Result<Self, regex::Error> {
let kind = if pattern.is_empty() || pattern == "*" {
MatcherKind::All
} else if is_simple_form(pattern) {
MatcherKind::Exact(exact_names(pattern))
} else {
MatcherKind::Regex(Regex::new(pattern)?)
};
Ok(Self { kind })
}
pub fn is_match(&self, tool_name: &str) -> bool {
match &self.kind {
MatcherKind::All => true,
MatcherKind::Exact(names) => names.iter().any(|n| n == tool_name),
MatcherKind::Regex(regex) => {
regex.is_match(tool_name)
|| claude_names_for(tool_name).any(|alias| regex.is_match(alias))
}
}
}
}
/// A pattern is "simple" (exact/`|`-list, not regex) when it contains only
/// ASCII alphanumerics, `_`, and `|`.
fn is_simple_form(pattern: &str) -> bool {
!pattern.is_empty()
&& pattern
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'|')
}
/// Expand a simple-form pattern into the exact set of names it matches: each `|`-term
/// plus any Grok tool names that term aliases (so `"Bash"` also matches
/// `run_terminal_command`), per the shared external-name to Grok registry in
/// `xai-grok-tools`. Empty terms and duplicates are dropped.
fn exact_names(pattern: &str) -> Vec<String> {
let mut names: Vec<String> = Vec::new();
let mut push = |name: &str| {
if !name.is_empty() && !names.iter().any(|n| n == name) {
names.push(name.to_string());
}
};
for term in pattern.split('|') {
push(term);
for grok_name in grok_names_for(term) {
push(grok_name);
}
}
names
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exact_match() {
let m = HookMatcher::new("run_terminal_command").unwrap();
assert!(m.is_match("run_terminal_command"));
assert!(!m.is_match("run_terminal_command_v2"));
assert!(!m.is_match("other_tool"));
}
#[test]
fn pipe_list_is_exact_per_term() {
let m = HookMatcher::new("read_file|list_dir").unwrap();
assert!(m.is_match("read_file"));
assert!(m.is_match("list_dir"));
assert!(!m.is_match("grep"));
// Regression for the old `^a|b$` anchoring bug: terms must not substring-match.
assert!(!m.is_match("my_read_file"));
assert!(!m.is_match("list_dir_v2"));
}
#[test]
fn pipe_skips_empty_terms() {
// Leading/trailing/double pipes contribute no spurious empty-string match.
let m = HookMatcher::new("|read_file||grep|").unwrap();
assert!(m.is_match("read_file"));
assert!(m.is_match("grep"));
assert!(!m.is_match(""));
}
#[test]
fn regex_form_is_unanchored() {
// Contains regex metachars -> regex mode, unanchored.
let m = HookMatcher::new("run_.*").unwrap();
assert!(m.is_match("run_terminal_command"));
assert!(m.is_match("xrun_yyy")); // unanchored: substring match
assert!(!m.is_match("read_file"));
}
#[test]
fn anchored_regex_respects_user_anchors() {
let m = HookMatcher::new("^run_.*$").unwrap();
assert!(m.is_match("run_terminal_command"));
assert!(!m.is_match("xrun_yyy"));
assert!(!m.is_match("read_file"));
}
#[test]
fn invalid_regex_errors() {
assert!(HookMatcher::new("[invalid").is_err());
}
#[test]
fn star_and_empty_match_all() {
for pat in ["*", ""] {
let m = HookMatcher::new(pat).unwrap();
assert!(m.is_match("read_file"), "{pat:?} should match all");
assert!(m.is_match("anything_at_all"), "{pat:?} should match all");
}
}
#[test]
fn whitespace_matcher_matches_nothing() {
// Whitespace is NOT trimmed; `" "` is a regex that matches no
// real tool name (NOT match-all, which would turn a deny gate into deny-all).
let m = HookMatcher::new(" ").unwrap();
assert!(!m.is_match("read_file"));
assert!(!m.is_match("run_terminal_command"));
}
// ── External tool-name aliases ────────────────────────────────
#[test]
fn claude_bash_matches_grok_tool() {
let m = HookMatcher::new("Bash").unwrap();
assert!(m.is_match("Bash")); // external alias name
assert!(m.is_match("run_terminal_command")); // Grok name
assert!(!m.is_match("read_file"));
// Bug-fix regression: exact, not prefix.
assert!(!m.is_match("run_terminal_command_v2"));
}
#[test]
fn claude_edit_write_matches_grok_tool_exactly() {
let m = HookMatcher::new("Edit|Write").unwrap();
assert!(m.is_match("Edit"));
assert!(m.is_match("Write"));
assert!(m.is_match("search_replace")); // Grok equivalent
assert!(m.is_match("hashline_edit")); // second Grok alias
assert!(!m.is_match("read_file"));
// The old anchoring bug matched these; the exact-list mode must not.
assert!(!m.is_match("Editorial"));
assert!(!m.is_match("my_search_replace"));
}
#[test]
fn claude_read_matches_grok_tool() {
let m = HookMatcher::new("Read").unwrap();
assert!(m.is_match("Read"));
assert!(m.is_match("read_file"));
assert!(m.is_match("hashline_read"));
}
#[test]
fn regex_against_claude_alias_matches_grok_tool() {
// A regex written against an external alias still matches the Grok tool
// (legacy alias-name expansion).
let m = HookMatcher::new("^Bash$").unwrap();
assert!(m.is_match("run_terminal_command"));
assert!(m.is_match("Bash"));
}
}

View file

@ -0,0 +1,70 @@
use std::time::Duration;
/// The outcome of a blocking (`pre_tool_use`) hook dispatch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HookDecision {
/// All hooks allowed (or no hooks matched).
Allow,
/// At least one hook denied with the given reason.
Deny { reason: String, hook_name: String },
}
/// HTTP-specific execution details for scrollback enrichment.
///
/// Populated only for `"http"` handler type hooks. Carries the target
/// URL, HTTP status, and a short preview of the response body so that
/// scrollback annotations can display them.
#[derive(Debug, Clone)]
pub struct HttpInfo {
/// The URL that was POSTed to.
///
/// **Post-expansion form**: this is the actual target the runner
/// hit (or attempted to hit) and is intended for SSRF debugging.
/// User `env` map values resolved at expand time can land here, so
/// any new wire-DTO consumer that surfaces this field for **user
/// display** MUST prefer [`raw_url`] when available -- otherwise
/// secrets like API tokens embedded in the URL via `${TOKEN}`
/// substitution will leak. See `HookSpec::url_raw` in
/// `crate::config` for the parallel display-vs-execution split.
///
/// [`raw_url`]: HttpInfo::raw_url
pub url: String,
/// Pre-expansion source URL exactly as written in the JSON file,
/// when available. Mirrors `HookSpec::url_raw` so downstream wire
/// DTOs / scrollback display layers can show the source string
/// without ever leaking resolved `${VAR}` substitutions. `None`
/// for legacy code paths that constructed the spec without the
/// raw source (the runner falls back to displaying [`url`] in
/// that case).
///
/// [`url`]: HttpInfo::url
pub raw_url: Option<String>,
/// HTTP status code (e.g. 200, 500). `None` if the request never
/// completed (timeout, connection error).
pub status: Option<u16>,
/// Short preview of the response body (truncated to ~200 chars).
/// `None` if no body was read (e.g. non-blocking hooks, timeouts).
pub response_preview: Option<String>,
}
/// The outcome of a single hook execution.
#[derive(Debug)]
pub enum HookRunResult {
/// Hook executed successfully.
Success {
hook_name: String,
elapsed: Duration,
/// HTTP details, populated only for `"http"` handler type hooks.
http_info: Option<HttpInfo>,
},
/// Hook was skipped because it is disabled.
Skipped { hook_name: String },
/// Hook failed (timeout, crash, bad output, etc.) — fail-open.
Failed {
hook_name: String,
error: String,
elapsed: Duration,
/// HTTP details, populated only for `"http"` handler type hooks.
http_info: Option<HttpInfo>,
},
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,953 @@
//! HTTP hook handler runner.
//!
//! Executes hooks by POSTing the event envelope JSON to a URL endpoint.
//! Supports the same blocking (deny/allow) response format as command hooks.
use std::net::IpAddr;
use std::time::{Duration, Instant};
use serde::Deserialize;
use url::Url;
use crate::config::HookSpec;
use crate::event::HookEventEnvelope;
use crate::result::{HookDecision, HttpInfo};
use super::{HookRunOutput, HookRunnerResult, RunContext};
/// Maximum characters to keep from the response body for the preview.
const RESPONSE_PREVIEW_MAX: usize = 200;
/// The JSON result structure expected from blocking HTTP hooks.
#[derive(Debug, Deserialize)]
struct HttpHookOutput {
decision: String,
#[serde(default)]
reason: Option<String>,
}
/// CWE-918: Returns `true` if an IP address is in a private, link-local,
/// or cloud metadata range that should be blocked to prevent SSRF attacks.
///
/// Loopback (`127.x` / `::1`) is allowed for local development servers.
fn is_blocked_ip(ip: &IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => {
let octets = v4.octets();
if octets[0] == 127 {
return false; // loopback — allowed for local dev
}
if octets[0] == 10 {
return true; // RFC 1918: 10.0.0.0/8
}
if octets[0] == 172 && (16..=31).contains(&octets[1]) {
return true; // RFC 1918: 172.16.0.0/12
}
if octets[0] == 192 && octets[1] == 168 {
return true; // RFC 1918: 192.168.0.0/16
}
if octets[0] == 169 && octets[1] == 254 {
return true; // RFC 3927: 169.254.0.0/16 (link-local, cloud metadata)
}
if octets[0] == 100 && (64..=127).contains(&octets[1]) {
return true; // RFC 6598: 100.64.0.0/10 (CGNAT)
}
if v4.is_unspecified() {
return true; // 0.0.0.0
}
false
}
IpAddr::V6(v6) => {
if v6.is_loopback() {
return false; // ::1 — allowed for local dev
}
if v6.is_unspecified() {
return true; // ::
}
if let Some(v4) = v6.to_ipv4_mapped() {
return is_blocked_ip(&IpAddr::V4(v4));
}
let segments = v6.segments();
if segments[0] & 0xffc0 == 0xfe80 {
return true; // fe80::/10 — link-local
}
if segments[0] & 0xfe00 == 0xfc00 {
return true; // fc00::/7 — unique local (ULA)
}
false
}
}
}
/// CWE-918: Validate a hook URL to prevent SSRF.
///
/// Requirements:
/// - Only HTTPS scheme is allowed (reject HTTP / other schemes).
/// - Resolved IP addresses must not be in private/link-local/metadata ranges.
async fn validate_hook_url(url: &str) -> Result<(), String> {
let parsed = Url::parse(url).map_err(|e| format!("invalid URL: {e}"))?;
// Restrict to HTTPS only.
if parsed.scheme() != "https" {
return Err(format!(
"only https:// URLs are allowed for HTTP hooks, got {}://",
parsed.scheme()
));
}
let host = parsed
.host_str()
.ok_or_else(|| "URL has no host".to_string())?;
// If host is a literal IP, check it directly.
if let Ok(ip) = host.parse::<IpAddr>() {
if is_blocked_ip(&ip) {
return Err(format!("URL resolves to blocked private/internal IP: {ip}"));
}
return Ok(());
}
// DNS resolution check.
let port = parsed.port_or_known_default().unwrap_or(443);
let addr_str = format!("{host}:{port}");
let addrs: Vec<std::net::SocketAddr> = tokio::net::lookup_host(&addr_str)
.await
.map_err(|e| format!("DNS resolution failed for {host}: {e}"))?
.collect();
if addrs.is_empty() {
return Err(format!("DNS resolved no addresses for {host}"));
}
for addr in &addrs {
if is_blocked_ip(&addr.ip()) {
return Err(format!(
"URL host {host} resolves to blocked private/internal IP: {}",
addr.ip()
));
}
}
Ok(())
}
/// Run a single HTTP hook.
///
/// POSTs the serialized `HookEventEnvelope` as JSON to `spec.url`.
/// For blocking hooks (`PreToolUse`), parses the response JSON for
/// `{"decision": "allow"}` or `{"decision": "deny", "reason": "..."}`.
/// For non-blocking hooks, any 2xx response is success.
///
/// Respects `spec.timeout_ms` for the entire request.
pub async fn run_http_hook(
spec: &HookSpec,
envelope: &HookEventEnvelope,
_ctx: &RunContext<'_>,
is_blocking: bool,
) -> HookRunOutput {
let start = Instant::now();
let Some(ref raw_url) = spec.url else {
return (
HookRunnerResult::Failed("http hook has no 'url' field".into()),
start.elapsed(),
None,
);
};
// Expand `${VAR}` / `$VAR` in the URL right before validation. We
// re-run expansion here (in addition to the load-time pass in
// `parse_hook_file`) because plugin URLs can reference plugin-injected
// vars (e.g. `${CLAUDE_PLUGIN_ROOT}/check`) that only land in
// `spec.extra_env` after the plugin adapter wires them in.
//
// For plugin hooks specifically: the load-time pass in
// `parse_hook_file` runs BEFORE the plugin adapter populates
// `extra_env` with plugin keys, so `${CLAUDE_PLUGIN_ROOT}` etc.
// survive that pass and are resolved here at runtime. For
// non-plugin hooks the load-time pass already resolved everything
// resolvable, and this pass is effectively a no-op.
//
// Unset refs are preserved verbatim, so `validate_hook_url` will
// reject them with an "invalid URL" error rather than silently
// smuggling a literal `${VAR}` past validation.
let expanded_url = crate::env_expand::expand_env_vars_with_extra(raw_url, &spec.extra_env);
let url: &str = &expanded_url;
// For tracing/log purposes prefer the pre-expansion source so
// resolved values from the user `env` map (which may contain
// secrets like API tokens) don't land in `~/.grok/logs`. Falls
// back to the expanded form if the spec was constructed by a
// legacy path that didn't populate `url_raw`. The same `log_url`
// is also threaded into `format!("HTTP request failed for {}:
// {}", log_url, e.without_url())` below so reqwest's default
// `Display` (which appends the request URL) does not bypass the
// raw-source preference.
let log_url: &str = spec.url_raw.as_deref().unwrap_or(url);
// Helper: build an `HttpInfo` populated with both the
// post-expansion `url` (for SSRF debugging) and the raw source
// form (for any user-facing display surface). See `HttpInfo`
// rustdoc on `crate::result::HttpInfo` for the contract.
let make_info = |status: Option<u16>, preview: Option<String>| -> HttpInfo {
HttpInfo {
url: url.to_owned(),
raw_url: spec.url_raw.clone(),
status,
response_preview: preview,
}
};
// CWE-918: Validate URL before sending any data.
if let Err(reason) = validate_hook_url(url).await {
tracing::warn!(
hook_name = %spec.name,
url = %log_url,
%reason,
"SSRF protection: blocked HTTP hook URL"
);
return (
HookRunnerResult::Failed(format!("blocked by SSRF protection: {reason}")),
start.elapsed(),
Some(make_info(None, None)),
);
}
let body = match serde_json::to_string(envelope) {
Ok(j) => j,
Err(e) => {
return (
HookRunnerResult::Failed(format!("failed to serialize envelope: {e}")),
start.elapsed(),
Some(make_info(None, None)),
);
}
};
let client = reqwest::Client::builder()
.timeout(Duration::from_millis(spec.timeout_ms))
.build()
.unwrap_or_default();
let response = match client
.post(url)
.header("Content-Type", "application/json")
.body(body)
.send()
.await
{
Ok(r) => r,
Err(e) => {
let elapsed = start.elapsed();
// SECURITY: `reqwest::Error::Display` unconditionally
// appends the request URL. If the resolved URL embeds a
// secret resolved from the user `env` map (e.g.
// `?token=ghp_REAL_SECRET`), the secret would otherwise
// land in `HookRunResult::Failed.error` and surface in
// pager scrollback / wire DTOs. `e.without_url()` strips
// the URL from the formatted output so we substitute our
// own `log_url` (which prefers the raw source form) in
// its place.
let error = if e.is_timeout() {
format!("timed out after {}ms", spec.timeout_ms)
} else {
format!("HTTP request failed for {}: {}", log_url, e.without_url())
};
return (
HookRunnerResult::Failed(error),
elapsed,
Some(make_info(None, None)),
);
}
};
let status = response.status();
let status_code = status.as_u16();
let elapsed = start.elapsed();
tracing::debug!(
hook_name = %spec.name,
url = %log_url,
status = status_code,
elapsed_ms = elapsed.as_millis() as u64,
"http hook completed"
);
if !is_blocking {
let http_info = Some(make_info(Some(status_code), None));
if status.is_success() {
return (HookRunnerResult::Success, elapsed, http_info);
}
return (
HookRunnerResult::Failed(format!("HTTP status {}", status)),
elapsed,
http_info,
);
}
// Blocking hook: parse response JSON for decision.
let response_text = match response.text().await {
Ok(t) => t,
Err(e) => {
// SECURITY: same `without_url()` reasoning as the send
// failure above -- reqwest's body-read error also includes
// the URL by default.
return (
HookRunnerResult::Failed(format!(
"failed to read response body for {}: {}",
log_url,
e.without_url()
)),
elapsed,
Some(make_info(Some(status_code), None)),
);
}
};
let response_preview = if response_text.trim().is_empty() {
None
} else {
Some(truncate_preview(&response_text))
};
let http_info = Some(make_info(Some(status_code), response_preview.clone()));
let result = parse_http_blocking_result(&response_text, status, &spec.name);
(result, elapsed, http_info)
}
/// Parse an HTTP blocking hook response into a `HookRunnerResult`.
///
/// This is the HTTP analogue of `command::parse_blocking_result`.
/// Extracted as a standalone function so it can be unit-tested without
/// making real HTTP requests.
fn parse_http_blocking_result(
response_text: &str,
status: reqwest::StatusCode,
hook_name: &str,
) -> HookRunnerResult {
if response_text.trim().is_empty() {
// No body: use HTTP status as fallback.
if status.is_success() {
return HookRunnerResult::Decision(HookDecision::Allow);
}
return HookRunnerResult::Failed(format!("HTTP status {} with empty body", status));
}
match serde_json::from_str::<HttpHookOutput>(response_text) {
Ok(output) => {
if output.decision == "deny" {
let reason = output
.reason
.unwrap_or_else(|| format!("denied by hook '{}'", hook_name));
HookRunnerResult::Decision(HookDecision::Deny {
reason,
hook_name: hook_name.to_string(),
})
} else if output.decision == "allow" {
HookRunnerResult::Decision(HookDecision::Allow)
} else {
HookRunnerResult::Failed(format!(
"unknown decision value '{}' from hook '{}'",
output.decision, hook_name
))
}
}
Err(e) => {
// Cannot parse response: fail-open if status is success.
if status.is_success() {
tracing::warn!(
hook_name = %hook_name,
error = %e,
"could not parse HTTP hook response JSON, treating as allow"
);
HookRunnerResult::Decision(HookDecision::Allow)
} else {
HookRunnerResult::Failed(format!(
"HTTP status {} and failed to parse response: {e}",
status
))
}
}
}
}
/// Truncate a response body string for preview display.
///
/// Uses `char_indices` to find a safe UTF-8 boundary so we never panic
/// on multi-byte characters.
fn truncate_preview(s: &str) -> String {
let trimmed = s.trim();
if trimmed.len() <= RESPONSE_PREVIEW_MAX {
trimmed.to_string()
} else {
// Find the last char boundary at or before RESPONSE_PREVIEW_MAX bytes.
let boundary = trimmed
.char_indices()
.take_while(|&(i, _)| i <= RESPONSE_PREVIEW_MAX)
.last()
.map(|(i, _)| i)
.unwrap_or(0);
let mut preview = trimmed[..boundary].to_string();
preview.push_str("...");
preview
}
}
#[cfg(test)]
mod tests {
use super::*;
use reqwest::StatusCode;
// ── parse_http_blocking_result tests ──────────────────────────
#[test]
fn http_allow_json() {
let result =
parse_http_blocking_result(r#"{"decision":"allow"}"#, StatusCode::OK, "test-hook");
assert!(matches!(
result,
HookRunnerResult::Decision(HookDecision::Allow)
));
}
#[test]
fn http_deny_json_with_reason() {
let result = parse_http_blocking_result(
r#"{"decision":"deny","reason":"dangerous command"}"#,
StatusCode::OK,
"test-hook",
);
match result {
HookRunnerResult::Decision(HookDecision::Deny { reason, hook_name }) => {
assert_eq!(reason, "dangerous command");
assert_eq!(hook_name, "test-hook");
}
other => panic!("expected Deny, got {other:?}"),
}
}
#[test]
fn http_deny_json_without_reason() {
let result =
parse_http_blocking_result(r#"{"decision":"deny"}"#, StatusCode::OK, "my-hook");
match result {
HookRunnerResult::Decision(HookDecision::Deny { reason, .. }) => {
assert!(
reason.contains("my-hook"),
"reason should mention hook name"
);
}
other => panic!("expected Deny, got {other:?}"),
}
}
#[test]
fn http_unknown_decision_fails() {
let result =
parse_http_blocking_result(r#"{"decision":"maybe"}"#, StatusCode::OK, "test-hook");
match result {
HookRunnerResult::Failed(msg) => {
assert!(msg.contains("maybe"));
assert!(msg.contains("test-hook"));
}
other => panic!("expected Failed, got {other:?}"),
}
}
#[test]
fn http_empty_body_success_allows() {
let result = parse_http_blocking_result("", StatusCode::OK, "test-hook");
assert!(matches!(
result,
HookRunnerResult::Decision(HookDecision::Allow)
));
}
#[test]
fn http_empty_body_whitespace_success_allows() {
let result = parse_http_blocking_result(" \n ", StatusCode::OK, "test-hook");
assert!(matches!(
result,
HookRunnerResult::Decision(HookDecision::Allow)
));
}
#[test]
fn http_empty_body_error_status_fails() {
let result = parse_http_blocking_result("", StatusCode::INTERNAL_SERVER_ERROR, "test-hook");
match result {
HookRunnerResult::Failed(msg) => {
assert!(msg.contains("500"));
assert!(msg.contains("empty body"));
}
other => panic!("expected Failed, got {other:?}"),
}
}
#[test]
fn http_invalid_json_success_status_fail_open() {
// Unparseable JSON with 200 OK should fail-open to allow.
let result = parse_http_blocking_result("not json at all", StatusCode::OK, "test-hook");
assert!(matches!(
result,
HookRunnerResult::Decision(HookDecision::Allow)
));
}
#[test]
fn http_invalid_json_error_status_fails() {
// Unparseable JSON with 500 should fail.
let result =
parse_http_blocking_result("not json", StatusCode::INTERNAL_SERVER_ERROR, "test-hook");
match result {
HookRunnerResult::Failed(msg) => {
assert!(msg.contains("500"));
}
other => panic!("expected Failed, got {other:?}"),
}
}
#[test]
fn http_deny_with_non_success_status() {
let result = parse_http_blocking_result(
r#"{"decision":"deny","reason":"forbidden"}"#,
StatusCode::FORBIDDEN,
"test-hook",
);
match result {
HookRunnerResult::Decision(HookDecision::Deny { reason, .. }) => {
assert_eq!(reason, "forbidden");
}
other => panic!("expected Deny, got {other:?}"),
}
}
#[test]
fn http_allow_with_non_success_status() {
let result = parse_http_blocking_result(
r#"{"decision":"allow"}"#,
StatusCode::BAD_REQUEST,
"test-hook",
);
assert!(matches!(
result,
HookRunnerResult::Decision(HookDecision::Allow)
));
}
#[test]
fn http_partial_json_success_fail_open() {
let result =
parse_http_blocking_result(r#"{"decision":"deny""#, StatusCode::OK, "test-hook");
assert!(matches!(
result,
HookRunnerResult::Decision(HookDecision::Allow)
));
}
#[test]
fn http_extra_fields_tolerated() {
let result = parse_http_blocking_result(
r#"{"decision":"deny","reason":"nope","extra":"ignored","count":42}"#,
StatusCode::OK,
"test-hook",
);
match result {
HookRunnerResult::Decision(HookDecision::Deny { reason, .. }) => {
assert_eq!(reason, "nope");
}
other => panic!("expected Deny, got {other:?}"),
}
}
// ── SSRF protection: is_blocked_ip tests ──────────────
#[test]
fn ssrf_blocks_rfc1918_10x() {
assert!(is_blocked_ip(&"10.0.0.1".parse().unwrap()));
assert!(is_blocked_ip(&"10.255.255.255".parse().unwrap()));
}
#[test]
fn ssrf_blocks_rfc1918_172x() {
assert!(is_blocked_ip(&"172.16.0.1".parse().unwrap()));
assert!(is_blocked_ip(&"172.31.255.255".parse().unwrap()));
assert!(!is_blocked_ip(&"172.15.0.1".parse().unwrap()));
assert!(!is_blocked_ip(&"172.32.0.1".parse().unwrap()));
}
#[test]
fn ssrf_blocks_rfc1918_192168() {
assert!(is_blocked_ip(&"192.168.0.1".parse().unwrap()));
assert!(is_blocked_ip(&"192.168.255.255".parse().unwrap()));
}
#[test]
fn ssrf_blocks_link_local_metadata() {
assert!(is_blocked_ip(&"169.254.0.1".parse().unwrap()));
assert!(is_blocked_ip(&"169.254.169.254".parse().unwrap()));
}
#[test]
fn ssrf_blocks_cgnat() {
assert!(is_blocked_ip(&"100.64.0.1".parse().unwrap()));
assert!(is_blocked_ip(&"100.127.255.255".parse().unwrap()));
assert!(!is_blocked_ip(&"100.63.0.1".parse().unwrap()));
}
#[test]
fn ssrf_blocks_unspecified() {
assert!(is_blocked_ip(&"0.0.0.0".parse().unwrap()));
assert!(is_blocked_ip(&"::".parse().unwrap()));
}
#[test]
fn ssrf_allows_loopback() {
assert!(!is_blocked_ip(&"127.0.0.1".parse().unwrap()));
assert!(!is_blocked_ip(&"::1".parse().unwrap()));
}
#[test]
fn ssrf_allows_public_ips() {
assert!(!is_blocked_ip(&"1.1.1.1".parse().unwrap()));
assert!(!is_blocked_ip(&"8.8.8.8".parse().unwrap()));
}
#[test]
fn ssrf_blocks_ipv6_link_local() {
assert!(is_blocked_ip(&"fe80::1".parse().unwrap()));
}
#[test]
fn ssrf_blocks_ipv6_unique_local() {
assert!(is_blocked_ip(&"fc00::1".parse().unwrap()));
assert!(is_blocked_ip(&"fd00::1".parse().unwrap()));
}
#[test]
fn ssrf_blocks_ipv4_mapped_ipv6_private() {
assert!(is_blocked_ip(&"::ffff:10.0.0.1".parse::<IpAddr>().unwrap()));
assert!(is_blocked_ip(
&"::ffff:192.168.1.1".parse::<IpAddr>().unwrap()
));
}
// ── SSRF protection: validate_hook_url tests ──────────
#[tokio::test]
async fn ssrf_rejects_http_scheme() {
let result = validate_hook_url("http://example.com/hook").await;
assert!(result.is_err());
assert!(result.unwrap_err().contains("https://"));
}
#[tokio::test]
async fn ssrf_rejects_ftp_scheme() {
let result = validate_hook_url("ftp://example.com/hook").await;
assert!(result.is_err());
assert!(result.unwrap_err().contains("https://"));
}
#[tokio::test]
async fn ssrf_rejects_private_ip_literal() {
let result = validate_hook_url("https://10.0.0.1/hook").await;
assert!(result.is_err());
assert!(result.unwrap_err().contains("blocked"));
}
#[tokio::test]
async fn ssrf_rejects_metadata_ip_literal() {
let result = validate_hook_url("https://169.254.169.254/latest/meta-data/").await;
assert!(result.is_err());
assert!(result.unwrap_err().contains("blocked"));
}
#[tokio::test]
async fn ssrf_allows_https_public_ip() {
let result = validate_hook_url("https://1.1.1.1/hook").await;
assert!(result.is_ok());
}
#[tokio::test]
async fn ssrf_rejects_invalid_url() {
let result = validate_hook_url("not a url").await;
assert!(result.is_err());
assert!(result.unwrap_err().contains("invalid URL"));
}
// ── URL env-var expansion (extra_env precedence) ───────────
use crate::config::HookSpec;
use crate::event::{HookEventEnvelope, HookEventName, HookPayload};
use crate::test_support::with_env_var;
/// Regression: an HTTP hook whose `url` references a var present only
/// in `spec.extra_env` (not the process env) must still be expanded
/// at runtime by `run_http_hook`. This is the path used by plugin
/// hooks where the plugin adapter wires `${CLAUDE_PLUGIN_ROOT}` into
/// `extra_env` after the load-time pass in `parse_hook_file` ran.
///
/// Documentation-of-intent unit test for the helper. The end-to-end
/// proof through `run_http_hook` lives in
/// [`run_http_hook_uses_post_expansion_url_for_ssrf`] below.
#[test]
fn url_extra_env_takes_precedence_in_runtime_expansion() {
// Use the same helper the runtime path uses; we don't need to
// make a real network call to verify the substitution, only that
// the helper resolves the right value from extra_env.
let mut extra = std::collections::HashMap::new();
extra.insert("PLUGIN_HOST".to_string(), "example.com".to_string());
let out =
crate::env_expand::expand_env_vars_with_extra("https://${PLUGIN_HOST}/check", &extra);
assert_eq!(out, "https://example.com/check");
}
/// If `extra_env` shadows a process-env var with the same name, the
/// `extra_env` value wins. This matches the contract documented on
/// `HookSpec::extra_env` and matches the lookup order in
/// `runner/command.rs`'s pre-flight check. Documentation-of-intent
/// unit test (the end-to-end variant via `run_http_hook` lives in
/// `tests/integration.rs`).
#[test]
fn url_extra_env_shadows_process_env() {
let key = "GROK_HOOKS_HTTP_TEST_SHADOW";
with_env_var(key, Some("from-process"), || {
let mut extra = std::collections::HashMap::new();
extra.insert(key.to_string(), "from-extra".to_string());
let out = crate::env_expand::expand_env_vars_with_extra(
&format!("https://${{{key}}}/x"),
&extra,
);
assert_eq!(out, "https://from-extra/x");
});
}
/// Regression: a URL with multiple `${VAR}` references must
/// expand all of them. Locks down behaviour against shellexpand
/// regressions that affect consecutive references.
#[test]
fn url_with_multiple_consecutive_env_refs_expands_all() {
let mut extra = std::collections::HashMap::new();
extra.insert("HOST".to_string(), "api.example.com".to_string());
extra.insert("PORT".to_string(), "8443".to_string());
extra.insert("ROUTE".to_string(), "v2/check".to_string());
let out = crate::env_expand::expand_env_vars_with_extra(
"https://${HOST}:${PORT}/${ROUTE}",
&extra,
);
assert_eq!(out, "https://api.example.com:8443/v2/check");
}
/// Regression: SSRF validation in `run_http_hook` must
/// operate on the POST-expansion URL. We construct a `HookSpec`
/// with `url: "https://${INTERNAL}/hook"` and `extra_env` mapping
/// `INTERNAL=10.0.0.1`, then call `run_http_hook` directly and
/// assert the failure carries SSRF-blocking language and that the
/// `HttpInfo.url` returned for scrollback is the post-expansion
/// form (`10.0.0.1`) rather than the literal placeholder.
#[tokio::test]
async fn run_http_hook_uses_post_expansion_url_for_ssrf() {
let mut extra_env = std::collections::HashMap::new();
extra_env.insert("INTERNAL_HOST_SSRF".to_string(), "10.0.0.1".to_string());
let raw = "https://${INTERNAL_HOST_SSRF}/hook";
let spec = HookSpec {
name: "test-ssrf-post-expand".into(),
event: HookEventName::PreToolUse,
handler_type: "http".into(),
configured_matcher: None,
matcher: None,
enabled: true,
command: None,
command_raw: None,
url: Some(raw.to_string()),
url_raw: Some(raw.to_string()),
timeout_ms: 1000,
source_dir: std::env::temp_dir(),
extra_env,
};
let envelope = HookEventEnvelope {
hook_event_name: HookEventName::PreToolUse,
session_id: "test".into(),
cwd: "/tmp".into(),
workspace_root: "/tmp".into(),
timestamp: "2025-01-01T00:00:00Z".into(),
transcript_path: None,
client_identifier: None,
prompt_id: None,
payload: HookPayload::PreToolUse {
tool_name: "test".into(),
tool_use_id: "id-1".into(),
tool_input: serde_json::json!({}),
tool_input_truncated: false,
permission_mode: None,
subagent_type: None,
},
};
let ctx = crate::runner::RunContext {
session_id: "test",
workspace_root: "/tmp",
};
let (result, _, info) = run_http_hook(&spec, &envelope, &ctx, true).await;
match result {
crate::runner::HookRunnerResult::Failed(reason) => {
assert!(
reason.contains("blocked") || reason.contains("SSRF"),
"expected SSRF block message, got: {reason}"
);
}
other => panic!("expected SSRF Failed, got {other:?}"),
}
let info = info.expect("HttpInfo should be present for SSRF block path");
assert_eq!(
info.url, "https://10.0.0.1/hook",
"HttpInfo.url must reflect the post-expansion URL (the actual target SSRF blocked)"
);
// HttpInfo.raw_url must mirror the source
// form so any future scrollback/wire-DTO consumer can prefer
// it for user-facing display.
assert_eq!(
info.raw_url.as_deref(),
Some("https://${INTERNAL_HOST_SSRF}/hook"),
"HttpInfo.raw_url must mirror HookSpec::url_raw"
);
}
/// Regression: `reqwest::Error::Display`
/// unconditionally appends the request URL. If the resolved URL
/// embeds a secret resolved via `${TOKEN}` substitution from the
/// user `env` map, the secret would land in
/// `HookRunResult::Failed.error` and surface in pager scrollback
/// without the raw-fields work catching it. This test
/// builds a HookSpec that resolves to a guaranteed-dead host
/// (TEST-NET-1 192.0.2.0/24 from RFC 5737, used in docs) with a
/// secret-bearing query string, calls run_http_hook, and asserts
/// the secret does NOT appear in the returned error message.
#[tokio::test]
async fn run_http_hook_scrubs_url_from_reqwest_error() {
// Use a TEST-NET-1 host (RFC 5737, "MUST NOT be used in
// public networks"). It is not RFC1918 so SSRF validation
// will let it through, but no real DNS or connection will
// succeed -- reqwest will surface a connection error whose
// default Display includes the URL.
let secret = "ghp_VERY_REAL_SECRET_TOKEN_42";
let mut extra_env = std::collections::HashMap::new();
extra_env.insert("RUNTIME_HOST".to_string(), "192.0.2.1".to_string());
extra_env.insert("MY_TOKEN".to_string(), secret.to_string());
let raw = "https://${RUNTIME_HOST}/check?token=${MY_TOKEN}";
let spec = HookSpec {
name: "test-scrub-reqwest-error".into(),
event: HookEventName::PreToolUse,
handler_type: "http".into(),
configured_matcher: None,
matcher: None,
enabled: true,
command: None,
command_raw: None,
url: Some(raw.to_string()),
url_raw: Some(raw.to_string()),
// Short timeout so the test doesn't hang waiting for the
// dead host. Still long enough to actually attempt the
// connection so we exercise the Err(e) branch of `send().await`.
timeout_ms: 500,
source_dir: std::env::temp_dir(),
extra_env,
};
let envelope = HookEventEnvelope {
hook_event_name: HookEventName::PreToolUse,
session_id: "test".into(),
cwd: "/tmp".into(),
workspace_root: "/tmp".into(),
timestamp: "2025-01-01T00:00:00Z".into(),
transcript_path: None,
client_identifier: None,
prompt_id: None,
payload: HookPayload::PreToolUse {
tool_name: "test".into(),
tool_use_id: "id-1".into(),
tool_input: serde_json::json!({}),
tool_input_truncated: false,
permission_mode: None,
subagent_type: None,
},
};
let ctx = crate::runner::RunContext {
session_id: "test",
workspace_root: "/tmp",
};
let (result, _, info) = run_http_hook(&spec, &envelope, &ctx, true).await;
// Either `Failed` (timeout / connection error) is fine; both
// exercise paths that previously embedded the raw URL via
// `format!("...{e}")`. Pure timeouts use a different
// formatting branch (no URL involved), so prefer the
// connection-error case but tolerate either.
let error_text = match result {
crate::runner::HookRunnerResult::Failed(reason) => reason,
other => panic!("expected Failed, got {other:?}"),
};
// The secret must NOT be in the error text. This covers BOTH
// the timeout branch (which doesn't format the URL at all,
// so trivially passes) and the connection-error branch
// (which formats `e.without_url()`, scrubbing the URL).
assert!(
!error_text.contains(secret),
"secret leaked into error text: {error_text}"
);
// The error must mention the raw URL form (so users can see
// which hook failed) -- never the resolved form, which would
// include the secret-bearing query string.
if !error_text.contains("timed out") {
// Connection-error branch: error must reference the raw
// form, not the resolved one.
assert!(
error_text.contains("${RUNTIME_HOST}") || error_text.contains("${MY_TOKEN}"),
"expected error to reference the raw URL form, got: {error_text}"
);
}
// HttpInfo.url is still post-expansion (intentional, for SSRF
// debugging). The wire-DTO consumer must prefer raw_url for
// display -- documented in the HttpInfo rustdoc.
let info = info.expect("HttpInfo should be present for connection failures too");
assert_eq!(
info.url,
"https://192.0.2.1/check?token=ghp_VERY_REAL_SECRET_TOKEN_42"
);
assert_eq!(info.raw_url.as_deref(), Some(raw));
}
/// Unresolved `${VAR}` refs are preserved verbatim by the helper,
/// which means `validate_hook_url` will reject the URL with an
/// "invalid URL" error. This is the desired behaviour: a hook
/// referencing an unset var must surface a clear failure rather than
/// silently smuggling the literal placeholder past validation.
#[tokio::test]
async fn url_unresolved_var_fails_validation() {
let key = "GROK_HOOKS_HTTP_TEST_UNRESOLVED";
// Step 1 (sync): ensure the var is unset and run the
// expansion. `with_env_var` uses `catch_unwind` so the closure
// is synchronous; we deliberately do the async `validate_hook_url`
// call OUTSIDE the helper so we don't try to nest tokio runtimes.
let expanded = with_env_var(key, None, || {
let extra = std::collections::HashMap::new();
crate::env_expand::expand_env_vars_with_extra(
&format!("https://${{{key}}}/check"),
&extra,
)
});
// The literal placeholder is preserved.
assert!(expanded.contains(&format!("${{{key}}}")));
// Url::parse rejects strings with literal `${` because `{`
// isn't a valid URL character.
let result = validate_hook_url(&expanded).await;
assert!(result.is_err(), "expected invalid URL error, got Ok");
}
}

View file

@ -0,0 +1,55 @@
pub mod command;
pub mod http;
use std::time::Duration;
use crate::config::HookSpec;
use crate::event::HookEventEnvelope;
use crate::result::{HookDecision, HttpInfo};
/// Context passed to any hook runner for environment setup.
pub struct RunContext<'a> {
pub session_id: &'a str,
pub workspace_root: &'a str,
}
/// Result of running a single hook (any handler type).
#[derive(Debug)]
pub enum HookRunnerResult {
/// Hook ran and produced a decision (for blocking hooks).
Decision(HookDecision),
/// Hook ran successfully (for non-blocking hooks).
Success,
/// Hook failed — caller should fail-open.
Failed(String),
}
/// Bundle returned by each runner: the result, wall-clock duration, and
/// optional HTTP metadata for enriched scrollback logging.
pub type HookRunOutput = (HookRunnerResult, Duration, Option<HttpInfo>);
/// Run a hook using the appropriate handler for its type.
///
/// Dispatches to `command::run_command_hook()` or `http::run_http_hook()`
/// based on `spec.handler_type`. Returns the result, elapsed duration, and
/// optional HTTP metadata for scrollback enrichment.
pub async fn run_hook(
spec: &HookSpec,
envelope: &HookEventEnvelope,
ctx: &RunContext<'_>,
is_blocking: bool,
) -> HookRunOutput {
match spec.handler_type.as_str() {
"command" => {
let (result, elapsed) =
command::run_command_hook(spec, envelope, ctx, is_blocking).await;
(result, elapsed, None)
}
"http" => http::run_http_hook(spec, envelope, ctx, is_blocking).await,
_ => (
HookRunnerResult::Failed(format!("unsupported handler type '{}'", spec.handler_type)),
Duration::ZERO,
None,
),
}
}

View file

@ -0,0 +1,122 @@
//! Test-only helpers shared across `xai-grok-hooks` unit + integration tests.
//!
//! This module is gated on `#[cfg(test)]` and is exported as `pub(crate)`
//! so any in-crate `#[cfg(test)] mod tests` can use it. Integration tests
//! under `tests/` cannot reach it; for those, copy or re-implement the
//! handful of functions here that they need (the only one currently used
//! by integration tests is unrelated).
use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
/// Run `f` with the env var `name` set to `value` (or unset if `value`
/// is `None`), restoring the previous value on return.
///
/// Uses `catch_unwind` so a panic inside `f` does not leak the env var
/// into the rest of the test process.
///
/// `cargo test` runs tests in parallel by default. Process env vars are
/// process-global, so callers should pick uniquely-named vars to avoid
/// inter-test races. The lifecycle here (save -> set -> run -> restore)
/// is panic-safe but not race-safe.
///
/// **FOLLOW-UP**: the helper does not
/// enforce the unique-name discipline -- a future contributor passing
/// a common name like `HOME` could trigger flaky tests. The standard
/// fix is to add `serial_test` as a dev-dep and decorate every
/// env-touching test with `#[serial(env_var)]` so the test runner
/// serialises them. For now the unique-name
/// convention plus `catch_unwind` restoration is sufficient for the
/// tests that ship today.
pub(crate) fn with_env_var<R>(name: &str, value: Option<&str>, f: impl FnOnce() -> R) -> R {
let previous = std::env::var_os(name);
// SAFETY: env-var writes are not thread-safe. Callers use uniquely
// named vars so no concurrent test races on the same name.
unsafe {
match value {
Some(v) => std::env::set_var(name, v),
None => std::env::remove_var(name),
}
}
let result = catch_unwind(AssertUnwindSafe(f));
// SAFETY: see above. Restore unconditionally so a panic doesn't
// leak env state to subsequent tests.
unsafe {
match previous {
Some(prev) => std::env::set_var(name, prev),
None => std::env::remove_var(name),
}
}
match result {
Ok(value) => value,
Err(payload) => resume_unwind(payload),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn restores_previous_value_on_normal_return() {
let key = "GROK_HOOKS_TEST_SUPPORT_RESTORE";
with_env_var(key, Some("first"), || {
with_env_var(key, Some("second"), || {
assert_eq!(std::env::var(key).unwrap(), "second");
});
assert_eq!(std::env::var(key).unwrap(), "first");
});
assert!(std::env::var(key).is_err());
}
#[test]
fn restores_previous_unset_state_on_normal_return() {
let key = "GROK_HOOKS_TEST_SUPPORT_UNSET_RESTORE";
// SAFETY: see module-level note.
unsafe {
std::env::remove_var(key);
}
with_env_var(key, Some("temporary"), || {
assert_eq!(std::env::var(key).unwrap(), "temporary");
});
assert!(std::env::var(key).is_err());
}
#[test]
fn restores_after_panic() {
let key = "GROK_HOOKS_TEST_SUPPORT_PANIC_RESTORE";
// SAFETY: see module-level note.
unsafe {
std::env::remove_var(key);
}
let panicked = catch_unwind(AssertUnwindSafe(|| {
with_env_var(key, Some("during-panic"), || {
panic!("intentional");
});
}));
assert!(panicked.is_err(), "expected panic to propagate");
assert!(
std::env::var(key).is_err(),
"env var must be restored after panic"
);
}
#[test]
fn allows_explicit_unset() {
let key = "GROK_HOOKS_TEST_SUPPORT_EXPLICIT_UNSET";
// SAFETY: see module-level note.
unsafe {
std::env::set_var(key, "before");
}
with_env_var(key, None, || {
assert!(std::env::var(key).is_err());
});
assert_eq!(std::env::var(key).unwrap(), "before");
// SAFETY: see module-level note.
unsafe {
std::env::remove_var(key);
}
}
}

View file

@ -0,0 +1,171 @@
use std::path::{Path, PathBuf};
// Project-hook trust is no longer stored here: the shell's folder-trust store
// (`~/.grok/trusted_folders.toml`) is the single authority for whether a repo's
// project hooks run (the same gate as repo-local MCP/LSP). The helpers below
// exist only to migrate prior grants out of the legacy file.
/// Path to the legacy project-hook trust file
/// (`<user_grok_home>/trusted-hook-projects`), or `None` when no user grok home
/// resolves. Retained only for the one-time migration into folder-trust.
pub fn legacy_trust_file_path() -> Option<PathBuf> {
Some(xai_grok_config::user_grok_home()?.join("trusted-hook-projects"))
}
/// Parse the legacy trusted-projects file into a list of project paths.
///
/// The legacy format is one canonical absolute path per line; blank and
/// `#`-comment lines are skipped. A missing file yields `Ok(empty)` (nothing to
/// migrate); any OTHER read error is returned as `Err` so the caller does not
/// mistake an unreadable file for an empty one and consume it. Consumed by the
/// one-time migration that seeds folder-trust from prior grants.
pub fn list_trusted_projects_with_file(trust_file: &Path) -> std::io::Result<Vec<PathBuf>> {
let content = match std::fs::read_to_string(trust_file) {
Ok(c) => c,
// A missing file is "nothing to migrate", not an error.
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(e),
};
Ok(content
.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.map(PathBuf::from)
.collect())
}
// ── Hook enable/disable ─────────────────────────────────────────────────
/// Check whether a hook is disabled by name.
///
/// Disabled hooks are listed in , one hook name per line.
pub fn is_hook_disabled(hook_name: &str) -> bool {
match disabled_hooks_file_path() {
Some(file) => is_hook_disabled_with_file(hook_name, &file),
None => false,
}
}
fn is_hook_disabled_with_file(hook_name: &str, file: &Path) -> bool {
let content = match std::fs::read_to_string(file) {
Ok(c) => c,
Err(_) => return false,
};
content
.lines()
.any(|l| !l.trim().is_empty() && !l.trim().starts_with('#') && l.trim() == hook_name)
}
/// Disable a hook by name. Adds to .
pub fn disable_hook(hook_name: &str) -> Result<(), String> {
let file = disabled_hooks_file_path()
.ok_or_else(|| "no user grok home (set $GROK_HOME or $HOME)".to_string())?;
disable_hook_with_file(hook_name, &file)
}
fn disable_hook_with_file(hook_name: &str, file: &Path) -> Result<(), String> {
if is_hook_disabled_with_file(hook_name, file) {
return Ok(()); // Already disabled.
}
if let Some(parent) = file.parent() {
let _ = std::fs::create_dir_all(parent);
}
use std::io::Write;
let mut f = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(file)
.map_err(|e| format!("failed to open disabled-hooks file: {e}"))?;
writeln!(f, "{hook_name}").map_err(|e| format!("failed to write disabled-hooks file: {e}"))?;
Ok(())
}
/// Enable a hook by name (remove from ).
pub fn enable_hook(hook_name: &str) -> Result<bool, String> {
match disabled_hooks_file_path() {
Some(file) => enable_hook_with_file(hook_name, &file),
None => Ok(false),
}
}
fn enable_hook_with_file(hook_name: &str, file: &Path) -> Result<bool, String> {
let content = match std::fs::read_to_string(file) {
Ok(c) => c,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(e) => return Err(format!("failed to read disabled-hooks file: {e}")),
};
let mut found = false;
let new_lines: Vec<&str> = content
.lines()
.filter(|line| {
let trimmed = line.trim();
if !trimmed.is_empty() && !trimmed.starts_with('#') && trimmed == hook_name {
found = true;
false
} else {
true
}
})
.collect();
if !found {
return Ok(false);
}
if let Some(parent) = file.parent() {
let _ = std::fs::create_dir_all(parent);
}
use std::io::Write;
let mut f = std::fs::File::create(file)
.map_err(|e| format!("failed to open disabled-hooks file: {e}"))?;
for line in new_lines {
writeln!(f, "{line}").map_err(|e| format!("failed to write disabled-hooks file: {e}"))?;
}
Ok(true)
}
/// Returns the path to `$GROK_HOME/disabled-hooks`, or `None` when no user grok
/// home resolves.
fn disabled_hooks_file_path() -> Option<PathBuf> {
Some(xai_grok_config::user_grok_home()?.join("disabled-hooks"))
}
#[cfg(test)]
mod tests {
use super::*;
/// Each test creates its own legacy file in its own temp dir -- no shared state.
fn trust_file_in(dir: &Path) -> PathBuf {
let grok_dir = dir.join(".grok");
std::fs::create_dir_all(&grok_dir).unwrap();
grok_dir.join("trusted-hook-projects")
}
#[test]
fn list_trusted_projects_parses_paths_skipping_comments_and_blanks() {
let home = tempfile::tempdir().unwrap();
let trust_file = trust_file_in(home.path());
std::fs::write(
&trust_file,
"# comment\n\n/abs/project/one\n /abs/project/two \n# trailing\n",
)
.unwrap();
let projects = list_trusted_projects_with_file(&trust_file).unwrap();
assert_eq!(
projects,
vec![
PathBuf::from("/abs/project/one"),
PathBuf::from("/abs/project/two"),
]
);
}
#[test]
fn list_trusted_projects_missing_file_is_empty() {
// A missing file is Ok(empty), NOT an error — so the migration treats it
// as "nothing to migrate" rather than as an unreadable file.
let projects =
list_trusted_projects_with_file(Path::new("/nonexistent/trusted-hook-projects"))
.expect("missing file resolves to Ok(empty)");
assert!(projects.is_empty());
}
}

View file

@ -0,0 +1,905 @@
//! Integration tests for xai-grok-hooks.
//!
//! These tests use inline shell command strings (routed via `sh -c`) to verify
//! the full dispatch pipeline: discovery → matching → execution → result.
//!
//! All hook commands are inline strings (containing spaces/pipes/semicolons)
//! rather than standalone executable script files. This avoids `noexec` tmpdir
//! issues in hermetic CI sandboxes where `chmod +x` on temp files may not work.
use std::path::Path;
use xai_grok_hooks::discovery::load_hooks;
use xai_grok_hooks::dispatcher;
use xai_grok_hooks::event::*;
use xai_grok_hooks::result::HookDecision;
use xai_grok_hooks::runner::RunContext;
/// Helper: write a JSON hook file.
fn write_hook(dir: &Path, filename: &str, content: &str) {
std::fs::write(dir.join(filename), content).unwrap();
}
/// Helper: create a pre_tool_use envelope.
fn pre_tool_use_envelope(tool_name: &str) -> HookEventEnvelope {
HookEventEnvelope {
hook_event_name: HookEventName::PreToolUse,
session_id: "test-session".into(),
cwd: "/tmp".into(),
workspace_root: "/tmp".into(),
timestamp: "2025-01-01T00:00:00Z".into(),
transcript_path: None,
client_identifier: None,
prompt_id: None,
payload: HookPayload::PreToolUse {
tool_name: tool_name.into(),
tool_use_id: "call-1".into(),
tool_input: serde_json::json!({"command": "echo hello"}),
tool_input_truncated: false,
permission_mode: None,
subagent_type: None,
},
}
}
/// Helper: create a session_start envelope.
fn session_start_envelope() -> HookEventEnvelope {
HookEventEnvelope {
hook_event_name: HookEventName::SessionStart,
session_id: "test-session".into(),
cwd: "/tmp".into(),
workspace_root: "/tmp".into(),
timestamp: "2025-01-01T00:00:00Z".into(),
transcript_path: None,
client_identifier: None,
prompt_id: None,
payload: HookPayload::SessionStart {
source: "new".into(),
model_id: None,
agent_type: None,
},
}
}
#[tokio::test]
async fn hook_allows_via_json() {
let dir = tempfile::tempdir().unwrap();
write_hook(
dir.path(),
"safety.json",
r#"{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"echo '{\"decision\":\"allow\"}'","timeout":3}]}]}}"#,
);
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty(), "errors: {errors:?}");
let ctx = RunContext {
session_id: "test",
workspace_root: dir.path().to_str().unwrap(),
};
let result = dispatcher::dispatch_pre_tool_use(
&registry,
&pre_tool_use_envelope("run_terminal_cmd"),
&ctx,
)
.await;
assert_eq!(result.decision, HookDecision::Allow);
}
#[tokio::test]
async fn hook_denies_via_json() {
let dir = tempfile::tempdir().unwrap();
// Inline command: echo deny JSON and exit 2.
write_hook(
dir.path(),
"safety.json",
r#"{"hooks":{"PreToolUse":[{"matcher":"run_terminal_cmd","hooks":[{"type":"command","command":"echo '{\"decision\":\"deny\",\"reason\":\"dangerous\"}'; exit 2","timeout":3}]}]}}"#,
);
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty());
let ctx = RunContext {
session_id: "test",
workspace_root: dir.path().to_str().unwrap(),
};
let result = dispatcher::dispatch_pre_tool_use(
&registry,
&pre_tool_use_envelope("run_terminal_cmd"),
&ctx,
)
.await;
match result.decision {
HookDecision::Deny { reason, .. } => {
assert_eq!(reason, "dangerous");
}
other => panic!("expected Deny, got {other:?}"),
}
}
#[tokio::test]
async fn hook_deny_via_exit_code_only() {
let dir = tempfile::tempdir().unwrap();
// Inline command: no JSON output, just exit code 2.
write_hook(
dir.path(),
"safety.json",
r#"{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"exit 2"}]}]}}"#,
);
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty());
let ctx = RunContext {
session_id: "test",
workspace_root: dir.path().to_str().unwrap(),
};
let pre_result =
dispatcher::dispatch_pre_tool_use(&registry, &pre_tool_use_envelope("read_file"), &ctx)
.await;
match pre_result.decision {
HookDecision::Deny { reason, .. } => {
assert!(reason.contains("exit code 2") || reason.contains("denied by hook"));
}
other => panic!("expected Deny, got {other:?}"),
}
}
#[tokio::test]
async fn hook_fail_open_on_crash() {
let dir = tempfile::tempdir().unwrap();
// Inline command: exit code 1 = hook failure. Under the fail-open
// policy the tool call must NOT be blocked; the failure is recorded
// for the UI but only an explicit `deny` decision blocks.
write_hook(
dir.path(),
"safety.json",
r#"{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"exit 1"}]}]}}"#,
);
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty());
let ctx = RunContext {
session_id: "test",
workspace_root: dir.path().to_str().unwrap(),
};
let pre_result =
dispatcher::dispatch_pre_tool_use(&registry, &pre_tool_use_envelope("read_file"), &ctx)
.await;
assert_eq!(
pre_result.decision,
HookDecision::Allow,
"fail-open: a crashing hook must not block the tool call"
);
assert_eq!(
pre_result.results.len(),
1,
"the failure must still appear in run_results for UI scrollback"
);
}
#[tokio::test]
async fn hook_fail_open_on_timeout() {
let dir = tempfile::tempdir().unwrap();
// Inline command: sleep longer than the timeout. Under fail-open
// the timeout must not block the tool call.
write_hook(
dir.path(),
"safety.json",
r#"{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"sleep 10","timeout":1}]}]}}"#,
);
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty());
let ctx = RunContext {
session_id: "test",
workspace_root: dir.path().to_str().unwrap(),
};
let pre_result =
dispatcher::dispatch_pre_tool_use(&registry, &pre_tool_use_envelope("read_file"), &ctx)
.await;
assert_eq!(
pre_result.decision,
HookDecision::Allow,
"fail-open: a timing-out hook must not block the tool call"
);
}
#[tokio::test]
async fn matcher_filters_tool_name() {
let dir = tempfile::tempdir().unwrap();
write_hook(
dir.path(),
"safety.json",
r#"{"hooks":{"PreToolUse":[{"matcher":"run_terminal_cmd","hooks":[{"type":"command","command":"echo '{\"decision\":\"deny\",\"reason\":\"blocked\"}'; exit 2"}]}]}}"#,
);
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty());
let ctx = RunContext {
session_id: "test",
workspace_root: dir.path().to_str().unwrap(),
};
// Matching tool name → denied.
let pre_result = dispatcher::dispatch_pre_tool_use(
&registry,
&pre_tool_use_envelope("run_terminal_cmd"),
&ctx,
)
.await;
assert!(matches!(pre_result.decision, HookDecision::Deny { .. }));
// Non-matching tool name → allowed (hook doesn't run).
let pre_result =
dispatcher::dispatch_pre_tool_use(&registry, &pre_tool_use_envelope("read_file"), &ctx)
.await;
assert_eq!(pre_result.decision, HookDecision::Allow);
}
#[tokio::test]
async fn non_blocking_dispatch() {
let dir = tempfile::tempdir().unwrap();
write_hook(
dir.path(),
"lifecycle.json",
r#"{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"echo session started"}]}]}}"#,
);
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty());
let ctx = RunContext {
session_id: "test",
workspace_root: dir.path().to_str().unwrap(),
};
let results = dispatcher::dispatch_non_blocking(
&registry,
HookEventName::SessionStart,
&session_start_envelope(),
&ctx,
)
.await;
assert_eq!(results.len(), 1);
assert!(matches!(
&results[0],
xai_grok_hooks::result::HookRunResult::Success { .. }
));
}
#[tokio::test]
async fn first_deny_stops_chain() {
let dir = tempfile::tempdir().unwrap();
// Two files: first denies, second allows. Second should never run.
write_hook(
dir.path(),
"01-deny.json",
r#"{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"echo '{\"decision\":\"deny\",\"reason\":\"first-deny\"}'; exit 2"}]}]}}"#,
);
write_hook(
dir.path(),
"02-allow.json",
r#"{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"echo '{\"decision\":\"allow\"}'"}]}]}}"#,
);
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty());
let ctx = RunContext {
session_id: "test",
workspace_root: dir.path().to_str().unwrap(),
};
let pre_result = dispatcher::dispatch_pre_tool_use(
&registry,
&pre_tool_use_envelope("run_terminal_cmd"),
&ctx,
)
.await;
match pre_result.decision {
HookDecision::Deny { reason, .. } => {
assert_eq!(reason, "first-deny");
}
other => panic!("expected Deny, got {other:?}"),
}
}
#[tokio::test]
async fn hook_receives_stdin_envelope() {
let dir = tempfile::tempdir().unwrap();
// Inline command: read stdin, check it contains expected fields, allow if valid.
write_hook(
dir.path(),
"check.json",
r#"{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"INPUT=$(cat); echo \"$INPUT\" | grep -q '\"hookEventName\"' && echo \"$INPUT\" | grep -q '\"toolName\"' && echo \"$INPUT\" | grep -q '\"sessionId\"' && echo '{\"decision\":\"allow\"}' || echo '{\"decision\":\"deny\",\"reason\":\"missing fields\"}'"}]}]}}"#,
);
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty());
let ctx = RunContext {
session_id: "test-sess-123",
workspace_root: dir.path().to_str().unwrap(),
};
let pre_result =
dispatcher::dispatch_pre_tool_use(&registry, &pre_tool_use_envelope("read_file"), &ctx)
.await;
assert_eq!(pre_result.decision, HookDecision::Allow);
}
#[tokio::test]
async fn hook_receives_env_vars() {
let dir = tempfile::tempdir().unwrap();
// Inline command: check env vars and write results to a file.
let output_file = dir.path().join("env_output.txt");
let cmd = format!(
r#"echo "EVENT=$GROK_HOOK_EVENT" > {f}; echo "NAME=$GROK_HOOK_NAME" >> {f}; echo "SESSION=$GROK_SESSION_ID" >> {f}; echo '{{"decision":"allow"}}'"#,
f = output_file.display(),
);
let hook_json = serde_json::json!({
"hooks": {
"PreToolUse": [
{ "hooks": [{ "type": "command", "command": cmd }] }
]
}
});
write_hook(dir.path(), "env.json", &hook_json.to_string());
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty());
let ctx = RunContext {
session_id: "sess-456",
workspace_root: dir.path().to_str().unwrap(),
};
let pre_result =
dispatcher::dispatch_pre_tool_use(&registry, &pre_tool_use_envelope("read_file"), &ctx)
.await;
assert_eq!(pre_result.decision, HookDecision::Allow);
// Verify env vars were received.
let output = std::fs::read_to_string(&output_file).unwrap();
assert!(output.contains("EVENT=pre_tool_use"), "output: {output}");
assert!(output.contains("NAME="), "output: {output}"); // auto-generated name
assert!(output.contains("SESSION=sess-456"), "output: {output}");
}
#[tokio::test]
async fn shell_pipe_command_works() {
let dir = tempfile::tempdir().unwrap();
// Shell command with a pipe -- must go through sh -c.
write_hook(
dir.path(),
"pipe.json",
r#"{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"cat | echo '{\"decision\":\"allow\"}'"}]}]}}"#,
);
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty());
let ctx = RunContext {
session_id: "test",
workspace_root: dir.path().to_str().unwrap(),
};
let pre_result =
dispatcher::dispatch_pre_tool_use(&registry, &pre_tool_use_envelope("read_file"), &ctx)
.await;
assert_eq!(pre_result.decision, HookDecision::Allow);
}
fn make_envelope(event: HookEventName, payload: HookPayload) -> HookEventEnvelope {
HookEventEnvelope {
hook_event_name: event,
session_id: "test-session".into(),
cwd: "/tmp".into(),
workspace_root: "/tmp".into(),
timestamp: "2025-01-01T00:00:00Z".into(),
transcript_path: None,
client_identifier: None,
prompt_id: None,
payload,
}
}
/// Each new event type: write hook file → load → dispatch → verify the
/// command fires and receives the correct JSON envelope on stdin.
#[tokio::test]
async fn new_event_types_fire_and_receive_correct_envelope() {
struct Case {
event_name: HookEventName,
json_key: &'static str,
payload: HookPayload,
assertions: Vec<(&'static str, serde_json::Value)>,
}
let cases = vec![
Case {
event_name: HookEventName::PostToolUseFailure,
json_key: "PostToolUseFailure",
payload: HookPayload::PostToolUseFailure {
tool_name: "run_terminal_cmd".into(),
tool_use_id: "call-1".into(),
tool_input: serde_json::json!({"command": "bad_cmd"}),
tool_input_truncated: false,
error: "command not found".into(),
subagent_type: None,
},
assertions: vec![
("hookEventName", "post_tool_use_failure".into()),
("toolName", "run_terminal_cmd".into()),
("error", "command not found".into()),
],
},
Case {
event_name: HookEventName::PermissionDenied,
json_key: "PermissionDenied",
payload: HookPayload::PermissionDenied {
tool_name: "run_terminal_cmd".into(),
tool_use_id: "call-2".into(),
tool_input: serde_json::json!({"command": "rm -rf /"}),
tool_input_truncated: false,
},
assertions: vec![
("hookEventName", "permission_denied".into()),
("toolName", "run_terminal_cmd".into()),
],
},
Case {
event_name: HookEventName::PreCompact,
json_key: "PreCompact",
payload: HookPayload::PreCompact {
source: "auto".into(),
},
assertions: vec![
("hookEventName", "pre_compact".into()),
("source", "auto".into()),
],
},
Case {
event_name: HookEventName::PostCompact,
json_key: "PostCompact",
payload: HookPayload::PostCompact {
source: "manual".into(),
},
assertions: vec![
("hookEventName", "post_compact".into()),
("source", "manual".into()),
],
},
Case {
event_name: HookEventName::StopFailure,
json_key: "StopFailure",
payload: HookPayload::StopFailure {
error: "rate_limit".into(),
},
assertions: vec![
("hookEventName", "stop_failure".into()),
("error", "rate_limit".into()),
],
},
];
for case in &cases {
let dir = tempfile::tempdir().unwrap();
let output_file = dir.path().join("output.json");
let cmd = format!("cat > {}", output_file.display());
let hook_json = serde_json::json!({
"hooks": {
(case.json_key): [
{ "hooks": [{ "type": "command", "command": cmd }] }
]
}
});
write_hook(dir.path(), "hook.json", &hook_json.to_string());
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(
errors.is_empty(),
"{}: load errors: {errors:?}",
case.json_key
);
assert!(!registry.is_empty(), "{}: registry empty", case.json_key);
let envelope = make_envelope(case.event_name, case.payload.clone());
let ctx = RunContext {
session_id: "test",
workspace_root: dir.path().to_str().unwrap(),
};
let results =
dispatcher::dispatch_non_blocking(&registry, case.event_name, &envelope, &ctx).await;
assert_eq!(
results.len(),
1,
"{}: expected 1 result, got {}",
case.json_key,
results.len()
);
assert!(
matches!(
&results[0],
xai_grok_hooks::result::HookRunResult::Success { .. }
),
"{}: hook did not succeed: {:?}",
case.json_key,
results[0]
);
let raw = std::fs::read_to_string(&output_file)
.unwrap_or_else(|e| panic!("{}: hook didn't fire: {e}", case.json_key));
let captured: serde_json::Value = serde_json::from_str(&raw)
.unwrap_or_else(|e| panic!("{}: bad JSON: {e}\nraw: {raw}", case.json_key));
for (field, expected) in &case.assertions {
assert_eq!(
&captured[field], expected,
"{}: field '{}' mismatch.\nExpected: {expected}\nGot: {}\nFull: {captured}",
case.json_key, field, captured[field]
);
}
}
}
/// Regression: a user JSON hook that declares `env` values for
/// runner-reserved keys (`GROK_HOOK_EVENT`, `GROK_HOOK_NAME`,
/// `GROK_SESSION_ID`, `GROK_WORKSPACE_ROOT`, `CLAUDE_PROJECT_DIR`)
/// must NOT spoof those values inside the spawned child. The
/// runner-injected vars always win at spawn time. This test
/// constructs the spoof JSON, dispatches a hook that writes `printenv`
/// for each key, and asserts the captured values are the runner's
/// authentic ones.
#[tokio::test]
async fn runner_injected_vars_override_extra_env_at_spawn() {
let dir = tempfile::tempdir().unwrap();
let output_file = dir.path().join("envcap.txt");
// The hook writes the values it sees for each reserved key.
let cmd = format!(
r#"echo "EVENT=$GROK_HOOK_EVENT" > {f}; echo "NAME=$GROK_HOOK_NAME" >> {f}; echo "SESSION=$GROK_SESSION_ID" >> {f}; echo "ROOT=$GROK_WORKSPACE_ROOT" >> {f}; echo "PROJ=$CLAUDE_PROJECT_DIR" >> {f}; echo "USER_KEY=$USER_KEY" >> {f}; echo '{{"decision":"allow"}}'"#,
f = output_file.display(),
);
let hook_json = serde_json::json!({
"hooks": {
"PreToolUse": [
{
"hooks": [
{
"type": "command",
"command": cmd,
// Spoof every reserved key + add a non-reserved one
// that should be preserved.
"env": {
"GROK_HOOK_EVENT": "spoofed_event",
"GROK_HOOK_NAME": "spoofed_name",
"GROK_SESSION_ID": "spoofed_session",
"GROK_WORKSPACE_ROOT": "/spoofed/root",
"CLAUDE_PROJECT_DIR": "/spoofed/project",
"USER_KEY": "user_value_kept"
}
}
]
}
]
}
});
write_hook(dir.path(), "spoof.json", &hook_json.to_string());
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty(), "errors: {errors:?}");
let real_session = "auth-session-xyz";
let real_workspace = dir.path().to_str().unwrap();
let ctx = RunContext {
session_id: real_session,
workspace_root: real_workspace,
};
let result =
dispatcher::dispatch_pre_tool_use(&registry, &pre_tool_use_envelope("read_file"), &ctx)
.await;
assert_eq!(result.decision, HookDecision::Allow);
let captured = std::fs::read_to_string(&output_file).unwrap();
// Reserved keys: runner values must win (NOT the spoofed values).
assert!(
captured.contains("EVENT=pre_tool_use"),
"GROK_HOOK_EVENT must reflect the real event, got:\n{captured}"
);
assert!(
!captured.contains("EVENT=spoofed_event"),
"spoofed GROK_HOOK_EVENT must NOT leak through, got:\n{captured}"
);
assert!(
captured.contains(&format!("SESSION={real_session}")),
"GROK_SESSION_ID must reflect the real session, got:\n{captured}"
);
assert!(
!captured.contains("SESSION=spoofed_session"),
"spoofed GROK_SESSION_ID must NOT leak through"
);
assert!(
captured.contains(&format!("ROOT={real_workspace}")),
"GROK_WORKSPACE_ROOT must reflect the real workspace root, got:\n{captured}"
);
assert!(
!captured.contains("ROOT=/spoofed/root"),
"spoofed GROK_WORKSPACE_ROOT must NOT leak through"
);
assert!(
captured.contains(&format!("PROJ={real_workspace}")),
"CLAUDE_PROJECT_DIR must reflect the real workspace root, got:\n{captured}"
);
assert!(
!captured.contains("PROJ=/spoofed/project"),
"spoofed CLAUDE_PROJECT_DIR must NOT leak through"
);
// Non-reserved key: user value passes through.
assert!(
captured.contains("USER_KEY=user_value_kept"),
"non-reserved user-declared env keys must pass through, got:\n{captured}"
);
}
/// Regression: a user JSON hook with `command:
/// "${VAR}/script.sh"` (no other shell metachars) should resolve at
/// load time to the substituted path and then take the **direct-exec**
/// branch in the runner. This proves the load-time -> direct-exec
/// path works end-to-end through `load_hooks` -> `dispatcher::dispatch_*`.
#[tokio::test]
async fn direct_exec_command_with_env_var_resolves_at_load_time() {
let dir = tempfile::tempdir().unwrap();
// Build an inline shell script via the env map: the resolved
// command path will be `<tmpdir>/check.sh`. We use the per-hook
// `env` map (rather than the process env) so this test doesn't
// need to mutate global state.
let tmpdir_str = dir.path().to_string_lossy().into_owned();
// Create the script in tempdir with executable bit.
let script = dir.path().join("check.sh");
std::fs::write(
&script,
"#!/bin/sh\necho '{\"decision\":\"allow\"}'\nexit 0\n",
)
.unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = std::fs::metadata(&script).unwrap().permissions();
perms.set_mode(0o755);
std::fs::set_permissions(&script, perms).unwrap();
}
let hook_json = serde_json::json!({
"hooks": {
"PreToolUse": [
{
"hooks": [
{
"type": "command",
// No shell metachars apart from `${...}`. The
// load-time pass resolves `${ROOT}` to the
// tmpdir path, leaving "/tmp.../check.sh"
// with NO `$` -- the runner picks the
// direct-exec branch.
"command": "${ROOT}/check.sh",
"env": { "ROOT": tmpdir_str }
}
]
}
]
}
});
write_hook(dir.path(), "exec.json", &hook_json.to_string());
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty(), "errors: {errors:?}");
// Sanity: the loaded spec already has the resolved path with no `$`.
let specs: Vec<_> = registry
.hooks_for(HookEventName::PreToolUse)
.iter()
.collect();
assert_eq!(specs.len(), 1);
let cmd = specs[0]
.command
.as_ref()
.unwrap()
.to_string_lossy()
.into_owned();
assert!(
!cmd.contains('$'),
"command must be fully resolved at load time, got: {cmd}"
);
assert!(cmd.ends_with("/check.sh"), "got: {cmd}");
let ctx = RunContext {
session_id: "test",
workspace_root: dir.path().to_str().unwrap(),
};
let result =
dispatcher::dispatch_pre_tool_use(&registry, &pre_tool_use_envelope("read_file"), &ctx)
.await;
assert_eq!(
result.decision,
HookDecision::Allow,
"direct-exec hook with env-var-resolved path must run, got {:?}",
result.decision
);
}
/// Regression: an HTTP hook whose `url` references `${VAR}`
/// resolved via the per-hook `env` map must reach the HTTP runner with
/// the post-expansion URL. We can't make a real network call from CI,
/// but we can prove the runner sees the expanded URL by pointing at a
/// blocked private IP and verifying the SSRF block message references
/// the post-expansion address. Pairs with the unit test
/// `run_http_hook_uses_post_expansion_url_for_ssrf`.
#[tokio::test]
async fn http_hook_url_env_expansion_end_to_end() {
let dir = tempfile::tempdir().unwrap();
let hook_json = serde_json::json!({
"hooks": {
"PreToolUse": [
{
"hooks": [
{
"type": "http",
// `${INTERNAL}` is in the per-hook env map
// and resolves to a private RFC1918 IP. The
// HTTP runner expands the URL, then SSRF
// validation rejects 10.0.0.1.
"url": "https://${INTERNAL}/check",
"env": { "INTERNAL": "10.0.0.1" }
}
]
}
]
}
});
write_hook(dir.path(), "http.json", &hook_json.to_string());
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty(), "errors: {errors:?}");
// Sanity: load-time expansion already substituted `${INTERNAL}`,
// because `INTERNAL` is in the per-hook env map (which feeds
// load-time expansion).
let specs: Vec<_> = registry
.hooks_for(HookEventName::PreToolUse)
.iter()
.collect();
assert_eq!(specs.len(), 1);
assert_eq!(
specs[0].url.as_deref(),
Some("https://10.0.0.1/check"),
"load-time expansion should have already substituted ${{INTERNAL}}"
);
// `url_raw` preserves the source string for display surfaces.
assert_eq!(
specs[0].url_raw.as_deref(),
Some("https://${INTERNAL}/check")
);
let ctx = RunContext {
session_id: "test",
workspace_root: dir.path().to_str().unwrap(),
};
let pre_result =
dispatcher::dispatch_pre_tool_use(&registry, &pre_tool_use_envelope("read_file"), &ctx)
.await;
// Fail-open: SSRF block is a hook failure, not a deny. The tool
// call is allowed; the failure is recorded for scrollback.
assert_eq!(
pre_result.decision,
HookDecision::Allow,
"fail-open: SSRF-blocked HTTP hook must NOT block the tool call"
);
assert_eq!(pre_result.results.len(), 1);
let run = &pre_result.results[0];
use xai_grok_hooks::result::HookRunResult;
let info = match run {
HookRunResult::Failed {
http_info, error, ..
} => {
assert!(
error.contains("blocked") || error.contains("SSRF"),
"expected SSRF block message, got: {error}"
);
http_info.as_ref().expect("HttpInfo should be present")
}
other => panic!("expected Failed run result, got {other:?}"),
};
assert_eq!(
info.url, "https://10.0.0.1/check",
"HttpInfo.url must reflect the post-expansion URL"
);
// raw_url mirrors the source string so wire-DTO
// consumers can prefer it over the post-expansion `url` for any
// user-facing display.
assert_eq!(
info.raw_url.as_deref(),
Some("https://${INTERNAL}/check"),
"HttpInfo.raw_url must mirror HookSpec::url_raw"
);
}
/// Mixed known + unknown events: known ones load and dispatch, unknown ones are skipped.
#[tokio::test]
async fn lenient_parsing_with_mixed_claude_events() {
let dir = tempfile::tempdir().unwrap();
let hook_json = serde_json::json!({
"hooks": {
"PreToolUse": [
{ "matcher": "run_terminal_cmd", "hooks": [{ "type": "command", "command": "echo '{\"decision\":\"allow\"}'" }] }
],
"PostToolUseFailure": [
{ "hooks": [{ "type": "command", "command": "echo fail-hook" }] }
],
"PreCompact": [
{ "hooks": [{ "type": "command", "command": "echo compact" }] }
],
// Unknown external-only events — must not break the above.
"PermissionRequest": [
{ "hooks": [{ "type": "command", "command": "echo perm-req" }] }
],
"TaskCreated": [
{ "hooks": [{ "type": "command", "command": "echo task" }] }
],
"FileChanged": [
{ "matcher": ".envrc", "hooks": [{ "type": "command", "command": "echo envrc" }] }
]
}
});
write_hook(dir.path(), "mixed.json", &hook_json.to_string());
let (registry, errors) = load_hooks(Some(dir.path()), None);
assert!(errors.is_empty(), "errors: {errors:?}");
assert_eq!(registry.hooks_for(HookEventName::PreToolUse).len(), 1);
assert_eq!(
registry.hooks_for(HookEventName::PostToolUseFailure).len(),
1
);
assert_eq!(registry.hooks_for(HookEventName::PreCompact).len(), 1);
let ctx = RunContext {
session_id: "test",
workspace_root: dir.path().to_str().unwrap(),
};
let result = dispatcher::dispatch_pre_tool_use(
&registry,
&pre_tool_use_envelope("run_terminal_cmd"),
&ctx,
)
.await;
assert_eq!(result.decision, HookDecision::Allow);
}