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            // No scratchpad layout researched for this harness yet (see docs/design/agent-scratchpad.md).
95            session_id: None,
96        })
97    }
98
99    fn render_response(&self, verdict: Verdict) -> HookResponse {
100        // A safe command → `allow`. Grok treats a hook `allow` as "declines to deny", NOT a grant:
101        // the command still runs grok's own permission gauntlet and may prompt (so safe-chains cannot
102        // auto-approve on grok — same as Cursor/Codex). Emitting it is honest and harmless, and
103        // becomes a real grant if grok ever promotes `allow`. `decision` is the top-level field grok
104        // reads (NOT Claude's `hookSpecificOutput.permissionDecision`). render_response is only
105        // called for ALLOWED verdicts; the Denied branch is defensive — it must stay empty (never
106        // emit allow) so a stray call can't fail open.
107        if verdict.is_allowed() {
108            HookResponse {
109                stdout: json!({ "decision": "allow" }).to_string(),
110                exit_code: 0,
111            }
112        } else {
113            HookResponse {
114                stdout: String::new(),
115                exit_code: 0,
116            }
117        }
118    }
119
120    /// Grok, like Codex/Cursor, has no hook `grant` and no hook `ask`: a hook can only DENY. A gated
121    /// command must therefore be vetoed — otherwise in `bypassPermissions`/`dontAsk` mode grok would
122    /// run it (the hook's `allow` only "declines to deny"). Deny protects in every mode; the escape
123    /// valve is a `~/.config/safe-chains.toml` grant or a grok `--allow` rule.
124    fn gated_policy(&self) -> super::GatedPolicy {
125        super::GatedPolicy::Deny
126    }
127
128    fn render_deny(&self, reason: &str) -> HookResponse {
129        // Both signals say deny: the top-level `decision` (honored regardless of exit code) and exit
130        // 2 (grok's deny code; any OTHER non-zero fails OPEN, so it must be exactly 2).
131        HookResponse {
132            stdout: json!({ "decision": "deny", "reason": reason }).to_string(),
133            exit_code: 2,
134        }
135    }
136}
137
138fn hook_file(binary: &str) -> Value {
139    json!({
140        "hooks": {
141            "PreToolUse": [{
142                "matcher": "Bash",
143                "hooks": [{
144                    "type": "command",
145                    "command": binary,
146                    "timeout": 10,
147                }]
148            }]
149        }
150    })
151}
152
153fn has_safe_chains_hook(settings: &Value) -> bool {
154    settings
155        .get("hooks")
156        .and_then(|h| h.get("PreToolUse"))
157        .and_then(|arr| arr.as_array())
158        .is_some_and(|entries| {
159            entries.iter().any(|entry| {
160                entry
161                    .get("hooks")
162                    .and_then(|h| h.as_array())
163                    .is_some_and(|hooks| {
164                        hooks.iter().any(|hook| {
165                            hook.get("command")
166                                .and_then(|c| c.as_str())
167                                .is_some_and(|cmd| cmd.contains("safe-chains"))
168                        })
169                    })
170            })
171        })
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177    use crate::verdict::SafetyLevel;
178
179    fn target() -> GrokTarget {
180        GrokTarget
181    }
182
183    #[test]
184    fn install_no_grok_dir_skips() {
185        let dir = tempfile::tempdir().unwrap();
186        assert!(matches!(target().install(dir.path()).unwrap(), InstallOutcome::Skipped { .. }));
187    }
188
189    #[test]
190    fn install_creates_dedicated_hook_file() {
191        let dir = tempfile::tempdir().unwrap();
192        std::fs::create_dir(dir.path().join(".grok")).unwrap();
193        let outcome = target().install(dir.path()).unwrap();
194        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
195        let path = dir.path().join(".grok/hooks/safe-chains.json");
196        assert!(path.is_file(), "must write ~/.grok/hooks/safe-chains.json");
197        let settings: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
198        assert!(has_safe_chains_hook(&settings));
199        // Nested under a top-level `hooks` object with a `PreToolUse` array (grok/Codex shape), never
200        // a flat top-level `PreToolUse` key.
201        assert!(settings.pointer("/hooks/PreToolUse").and_then(|a| a.as_array()).is_some());
202        assert!(settings.get("PreToolUse").is_none());
203        assert_eq!(settings.pointer("/hooks/PreToolUse/0/matcher").and_then(|m| m.as_str()), Some("Bash"));
204    }
205
206    #[test]
207    fn install_uses_subcommand_invocation() {
208        let dir = tempfile::tempdir().unwrap();
209        std::fs::create_dir(dir.path().join(".grok")).unwrap();
210        target().install(dir.path()).unwrap();
211        let contents = std::fs::read_to_string(dir.path().join(".grok/hooks/safe-chains.json")).unwrap();
212        assert!(contents.contains("safe-chains hook grok"));
213    }
214
215    #[test]
216    fn install_idempotent() {
217        let dir = tempfile::tempdir().unwrap();
218        std::fs::create_dir(dir.path().join(".grok")).unwrap();
219        target().install(dir.path()).unwrap();
220        assert!(matches!(target().install(dir.path()).unwrap(), InstallOutcome::AlreadyConfigured { .. }));
221    }
222
223    // The verbatim PreToolUse envelope from ~/.grok/docs/user-guide/10-hooks.md — camelCase, with the
224    // command nested at toolInput.command and the project root at workspaceRoot.
225    const GROK_DOCS_SAMPLE: &str = r#"{
226        "hookEventName": "pre_tool_use",
227        "sessionId": "abc-123",
228        "cwd": "/Users/me/project/sub",
229        "workspaceRoot": "/Users/me/project",
230        "toolName": "run_terminal_command",
231        "toolInput": {"command": "npm test"},
232        "timestamp": "2026-07-22T00:00:00Z"
233    }"#;
234
235    #[test]
236    fn parse_input_extracts_camelcase_command_and_root() {
237        let parsed = GrokHookFormat.parse_input(GROK_DOCS_SAMPLE).unwrap();
238        assert_eq!(parsed.command, "npm test");
239        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project/sub"));
240        assert_eq!(parsed.root.as_deref(), Some("/Users/me/project"));
241    }
242
243    #[test]
244    fn parse_input_rejects_snake_case_envelope() {
245        // The Claude/Codex snake_case shape must NOT parse — if it did, grok's camelCase payload would
246        // silently fail to parse and fail OPEN. This is the casing tripwire.
247        let snake = r#"{"tool_input": {"command": "ls"}, "workspace_root": "/p"}"#;
248        assert!(GrokHookFormat.parse_input(snake).is_err());
249    }
250
251    #[test]
252    fn parse_input_rejects_garbage() {
253        assert!(GrokHookFormat.parse_input("not json").is_err());
254        assert!(GrokHookFormat.parse_input("{}").is_err());
255    }
256
257    #[test]
258    fn grok_is_a_deny_harness() {
259        assert_eq!(GrokHookFormat.gated_policy(), super::super::GatedPolicy::Deny);
260    }
261
262    #[test]
263    fn render_response_uses_top_level_decision_allow() {
264        // Grok reads a TOP-LEVEL `decision`, not Claude's `hookSpecificOutput.permissionDecision` nor
265        // Cursor's `permission`. Wiring this wrong fails open — pinned here.
266        let r = GrokHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
267        let v: Value = serde_json::from_str(&r.stdout).unwrap();
268        assert_eq!(v.get("decision").and_then(|d| d.as_str()), Some("allow"));
269        assert!(v.get("permissionDecision").is_none());
270        assert!(v.get("permission").is_none());
271        assert_eq!(r.exit_code, 0);
272    }
273
274    #[test]
275    fn render_response_denied_is_empty_fail_safe() {
276        // render_response is only called for ALLOWED verdicts; a defensive call with Denied must NOT
277        // emit an allow (else a stray call fails open). Pinned by the cross-target contract test too.
278        let r = GrokHookFormat.render_response(Verdict::Denied);
279        assert_eq!(r.stdout, "");
280    }
281
282    #[test]
283    fn render_deny_uses_decision_deny_and_exit_2() {
284        let r = GrokHookFormat.render_deny("blocked: not on the allowlist");
285        let v: Value = serde_json::from_str(&r.stdout).unwrap();
286        assert_eq!(v.get("decision").and_then(|d| d.as_str()), Some("deny"));
287        assert_eq!(v.get("reason").and_then(|d| d.as_str()), Some("blocked: not on the allowlist"));
288        assert!(v.get("permissionDecision").is_none());
289        // Exit 2 is grok's deny code; any OTHER non-zero fails OPEN, so this must be exactly 2.
290        assert_eq!(r.exit_code, 2);
291    }
292
293    #[test]
294    fn render_context_defaults_to_abstain() {
295        // Grok's PreToolUse output has no additionalContext channel, so context injection keeps the
296        // safe default: emit nothing.
297        let r = GrokHookFormat.render_context("anything");
298        assert_eq!(r.stdout, "");
299        assert_eq!(r.exit_code, 0);
300    }
301}