Skip to main content

safe_chains/targets/
grok.rs

1use std::path::{Path, PathBuf};
2
3use serde::Deserialize;
4use serde_json::{Value, json};
5
6use super::{HookFormat, HookInput, HookResponse, InstallOutcome, ParseError, Target};
7use crate::verdict::Verdict;
8
9pub struct GrokTarget;
10
11impl Target for GrokTarget {
12    fn name(&self) -> &'static str {
13        "grok"
14    }
15
16    fn display_name(&self) -> &'static str {
17        "Grok CLI (xAI)"
18    }
19
20    fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
21        vec![home.join(".grok")]
22    }
23
24    /// Grok discovers hooks from every `~/.grok/hooks/*.json` (globally trusted, no folder-trust
25    /// needed), so we own a DEDICATED `safe-chains.json` rather than editing a shared file — no risk
26    /// of clobbering the user's other hook files, and idempotency is trivial.
27    fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
28        let dir = home.join(".grok");
29        if !dir.exists() {
30            return Ok(InstallOutcome::Skipped {
31                reason: format!("~/.grok not found at {} (Grok CLI not installed)", dir.display()),
32            });
33        }
34
35        let hooks_dir = dir.join("hooks");
36        let path = hooks_dir.join("safe-chains.json");
37        let binary = "safe-chains hook grok";
38
39        if path.exists()
40            && let Ok(contents) = std::fs::read_to_string(&path)
41            && let Ok(value) = serde_json::from_str::<Value>(&contents)
42            && has_safe_chains_hook(&value)
43        {
44            return Ok(InstallOutcome::AlreadyConfigured { path });
45        }
46
47        std::fs::create_dir_all(&hooks_dir)
48            .map_err(|e| format!("Could not create {}: {e}", hooks_dir.display()))?;
49        let output = serde_json::to_string_pretty(&hook_file(binary)).expect("serializing valid JSON");
50        std::fs::write(&path, format!("{output}\n"))
51            .map_err(|e| format!("Could not write {}: {e}", path.display()))?;
52        Ok(InstallOutcome::Installed { path })
53    }
54
55    fn hook_format(&self) -> Option<&dyn HookFormat> {
56        Some(&GrokHookFormat)
57    }
58}
59
60struct GrokHookFormat;
61
62#[derive(Deserialize)]
63#[serde(rename_all = "camelCase")]
64struct GrokToolInput {
65    command: String,
66}
67
68#[derive(Deserialize)]
69#[serde(rename_all = "camelCase")]
70struct GrokHookEnvelope {
71    tool_input: GrokToolInput,
72    #[serde(default)]
73    cwd: Option<String>,
74    #[serde(default)]
75    workspace_root: Option<String>,
76}
77
78impl HookFormat for GrokHookFormat {
79    /// Grok's PreToolUse envelope is camelCase (`toolInput.command`, `workspaceRoot`) — unlike
80    /// Claude/Codex snake_case. Getting the casing wrong parses to nothing and fails OPEN, so it is
81    /// pinned by `parse_input_rejects_snake_case_envelope` below.
82    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
83        let envelope: GrokHookEnvelope =
84            serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
85        Ok(HookInput {
86            command: envelope.tool_input.command,
87            cwd: envelope.cwd,
88            // The project root arrives in the payload as `workspaceRoot`; grok also exports it as
89            // `GROK_WORKSPACE_ROOT` and (for Claude compat) `CLAUDE_PROJECT_DIR`.
90            root: envelope
91                .workspace_root
92                .or_else(|| super::env_root("GROK_WORKSPACE_ROOT"))
93                .or_else(|| super::env_root("CLAUDE_PROJECT_DIR")),
94        })
95    }
96
97    fn render_response(&self, verdict: Verdict) -> HookResponse {
98        // A safe command → `allow`. Grok treats a hook `allow` as "declines to deny", NOT a grant:
99        // the command still runs grok's own permission gauntlet and may prompt (so safe-chains cannot
100        // auto-approve on grok — same as Cursor/Codex). Emitting it is honest and harmless, and
101        // becomes a real grant if grok ever promotes `allow`. `decision` is the top-level field grok
102        // reads (NOT Claude's `hookSpecificOutput.permissionDecision`). render_response is only
103        // called for ALLOWED verdicts; the Denied branch is defensive — it must stay empty (never
104        // emit allow) so a stray call can't fail open.
105        if verdict.is_allowed() {
106            HookResponse {
107                stdout: json!({ "decision": "allow" }).to_string(),
108                exit_code: 0,
109            }
110        } else {
111            HookResponse {
112                stdout: String::new(),
113                exit_code: 0,
114            }
115        }
116    }
117
118    /// Grok, like Codex/Cursor, has no hook `grant` and no hook `ask`: a hook can only DENY. A gated
119    /// command must therefore be vetoed — otherwise in `bypassPermissions`/`dontAsk` mode grok would
120    /// run it (the hook's `allow` only "declines to deny"). Deny protects in every mode; the escape
121    /// valve is a `~/.config/safe-chains.toml` grant or a grok `--allow` rule.
122    fn gated_policy(&self) -> super::GatedPolicy {
123        super::GatedPolicy::Deny
124    }
125
126    fn render_deny(&self, reason: &str) -> HookResponse {
127        // Both signals say deny: the top-level `decision` (honored regardless of exit code) and exit
128        // 2 (grok's deny code; any OTHER non-zero fails OPEN, so it must be exactly 2).
129        HookResponse {
130            stdout: json!({ "decision": "deny", "reason": reason }).to_string(),
131            exit_code: 2,
132        }
133    }
134}
135
136fn hook_file(binary: &str) -> Value {
137    json!({
138        "hooks": {
139            "PreToolUse": [{
140                "matcher": "Bash",
141                "hooks": [{
142                    "type": "command",
143                    "command": binary,
144                    "timeout": 10,
145                }]
146            }]
147        }
148    })
149}
150
151fn has_safe_chains_hook(settings: &Value) -> bool {
152    settings
153        .get("hooks")
154        .and_then(|h| h.get("PreToolUse"))
155        .and_then(|arr| arr.as_array())
156        .is_some_and(|entries| {
157            entries.iter().any(|entry| {
158                entry
159                    .get("hooks")
160                    .and_then(|h| h.as_array())
161                    .is_some_and(|hooks| {
162                        hooks.iter().any(|hook| {
163                            hook.get("command")
164                                .and_then(|c| c.as_str())
165                                .is_some_and(|cmd| cmd.contains("safe-chains"))
166                        })
167                    })
168            })
169        })
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175    use crate::verdict::SafetyLevel;
176
177    fn target() -> GrokTarget {
178        GrokTarget
179    }
180
181    #[test]
182    fn install_no_grok_dir_skips() {
183        let dir = tempfile::tempdir().unwrap();
184        assert!(matches!(target().install(dir.path()).unwrap(), InstallOutcome::Skipped { .. }));
185    }
186
187    #[test]
188    fn install_creates_dedicated_hook_file() {
189        let dir = tempfile::tempdir().unwrap();
190        std::fs::create_dir(dir.path().join(".grok")).unwrap();
191        let outcome = target().install(dir.path()).unwrap();
192        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
193        let path = dir.path().join(".grok/hooks/safe-chains.json");
194        assert!(path.is_file(), "must write ~/.grok/hooks/safe-chains.json");
195        let settings: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
196        assert!(has_safe_chains_hook(&settings));
197        // Nested under a top-level `hooks` object with a `PreToolUse` array (grok/Codex shape), never
198        // a flat top-level `PreToolUse` key.
199        assert!(settings.pointer("/hooks/PreToolUse").and_then(|a| a.as_array()).is_some());
200        assert!(settings.get("PreToolUse").is_none());
201        assert_eq!(settings.pointer("/hooks/PreToolUse/0/matcher").and_then(|m| m.as_str()), Some("Bash"));
202    }
203
204    #[test]
205    fn install_uses_subcommand_invocation() {
206        let dir = tempfile::tempdir().unwrap();
207        std::fs::create_dir(dir.path().join(".grok")).unwrap();
208        target().install(dir.path()).unwrap();
209        let contents = std::fs::read_to_string(dir.path().join(".grok/hooks/safe-chains.json")).unwrap();
210        assert!(contents.contains("safe-chains hook grok"));
211    }
212
213    #[test]
214    fn install_idempotent() {
215        let dir = tempfile::tempdir().unwrap();
216        std::fs::create_dir(dir.path().join(".grok")).unwrap();
217        target().install(dir.path()).unwrap();
218        assert!(matches!(target().install(dir.path()).unwrap(), InstallOutcome::AlreadyConfigured { .. }));
219    }
220
221    // The verbatim PreToolUse envelope from ~/.grok/docs/user-guide/10-hooks.md — camelCase, with the
222    // command nested at toolInput.command and the project root at workspaceRoot.
223    const GROK_DOCS_SAMPLE: &str = r#"{
224        "hookEventName": "pre_tool_use",
225        "sessionId": "abc-123",
226        "cwd": "/Users/me/project/sub",
227        "workspaceRoot": "/Users/me/project",
228        "toolName": "run_terminal_command",
229        "toolInput": {"command": "npm test"},
230        "timestamp": "2026-07-22T00:00:00Z"
231    }"#;
232
233    #[test]
234    fn parse_input_extracts_camelcase_command_and_root() {
235        let parsed = GrokHookFormat.parse_input(GROK_DOCS_SAMPLE).unwrap();
236        assert_eq!(parsed.command, "npm test");
237        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project/sub"));
238        assert_eq!(parsed.root.as_deref(), Some("/Users/me/project"));
239    }
240
241    #[test]
242    fn parse_input_rejects_snake_case_envelope() {
243        // The Claude/Codex snake_case shape must NOT parse — if it did, grok's camelCase payload would
244        // silently fail to parse and fail OPEN. This is the casing tripwire.
245        let snake = r#"{"tool_input": {"command": "ls"}, "workspace_root": "/p"}"#;
246        assert!(GrokHookFormat.parse_input(snake).is_err());
247    }
248
249    #[test]
250    fn parse_input_rejects_garbage() {
251        assert!(GrokHookFormat.parse_input("not json").is_err());
252        assert!(GrokHookFormat.parse_input("{}").is_err());
253    }
254
255    #[test]
256    fn grok_is_a_deny_harness() {
257        assert_eq!(GrokHookFormat.gated_policy(), super::super::GatedPolicy::Deny);
258    }
259
260    #[test]
261    fn render_response_uses_top_level_decision_allow() {
262        // Grok reads a TOP-LEVEL `decision`, not Claude's `hookSpecificOutput.permissionDecision` nor
263        // Cursor's `permission`. Wiring this wrong fails open — pinned here.
264        let r = GrokHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
265        let v: Value = serde_json::from_str(&r.stdout).unwrap();
266        assert_eq!(v.get("decision").and_then(|d| d.as_str()), Some("allow"));
267        assert!(v.get("permissionDecision").is_none());
268        assert!(v.get("permission").is_none());
269        assert_eq!(r.exit_code, 0);
270    }
271
272    #[test]
273    fn render_response_denied_is_empty_fail_safe() {
274        // render_response is only called for ALLOWED verdicts; a defensive call with Denied must NOT
275        // emit an allow (else a stray call fails open). Pinned by the cross-target contract test too.
276        let r = GrokHookFormat.render_response(Verdict::Denied);
277        assert_eq!(r.stdout, "");
278    }
279
280    #[test]
281    fn render_deny_uses_decision_deny_and_exit_2() {
282        let r = GrokHookFormat.render_deny("blocked: not on the allowlist");
283        let v: Value = serde_json::from_str(&r.stdout).unwrap();
284        assert_eq!(v.get("decision").and_then(|d| d.as_str()), Some("deny"));
285        assert_eq!(v.get("reason").and_then(|d| d.as_str()), Some("blocked: not on the allowlist"));
286        assert!(v.get("permissionDecision").is_none());
287        // Exit 2 is grok's deny code; any OTHER non-zero fails OPEN, so this must be exactly 2.
288        assert_eq!(r.exit_code, 2);
289    }
290
291    #[test]
292    fn render_context_defaults_to_abstain() {
293        // Grok's PreToolUse output has no additionalContext channel, so context injection keeps the
294        // safe default: emit nothing.
295        let r = GrokHookFormat.render_context("anything");
296        assert_eq!(r.stdout, "");
297        assert_eq!(r.exit_code, 0);
298    }
299}