Skip to main content

safe_chains/targets/
gemini.rs

1use std::path::{Path, PathBuf};
2
3use serde::Deserialize;
4use serde_json::{Map, Value, json};
5
6use super::{HookFormat, HookInput, HookResponse, InstallOutcome, ParseError, Target, allow_reason};
7use crate::verdict::Verdict;
8
9pub struct GeminiTarget;
10
11impl Target for GeminiTarget {
12    fn name(&self) -> &'static str {
13        "gemini"
14    }
15
16    fn display_name(&self) -> &'static str {
17        "Gemini CLI"
18    }
19
20    fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
21        vec![home.join(".gemini")]
22    }
23
24    fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
25        let dir = home.join(".gemini");
26        if !dir.exists() {
27            return Ok(InstallOutcome::Skipped {
28                reason: format!(
29                    "~/.gemini not found at {} (Gemini CLI not installed)",
30                    dir.display()
31                ),
32            });
33        }
34
35        let path = dir.join("settings.json");
36        let binary = "safe-chains hook gemini";
37
38        if path.exists() {
39            let contents = std::fs::read_to_string(&path)
40                .map_err(|e| format!("Could not read {}: {e}", path.display()))?;
41            let mut settings: Value = serde_json::from_str(&contents)
42                .map_err(|e| format!("Could not parse {}: {e}", path.display()))?;
43
44            if has_safe_chains_hook(&settings) {
45                return Ok(InstallOutcome::AlreadyConfigured { path });
46            }
47
48            add_hook(&mut settings, binary);
49            let output = serde_json::to_string_pretty(&settings).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        } else {
54            let mut settings = Value::Object(Map::new());
55            add_hook(&mut settings, binary);
56            let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
57            std::fs::write(&path, format!("{output}\n"))
58                .map_err(|e| format!("Could not write {}: {e}", path.display()))?;
59            Ok(InstallOutcome::Installed { path })
60        }
61    }
62
63    fn hook_format(&self) -> Option<&dyn HookFormat> {
64        Some(&GeminiHookFormat)
65    }
66}
67
68struct GeminiHookFormat;
69
70#[derive(Deserialize)]
71struct ToolInput {
72    command: String,
73}
74
75#[derive(Deserialize)]
76struct GeminiHookEnvelope {
77    #[serde(default)]
78    tool_name: Option<String>,
79    tool_input: ToolInput,
80    #[serde(default)]
81    cwd: Option<String>,
82}
83
84impl HookFormat for GeminiHookFormat {
85    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
86        let envelope: GeminiHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError {
87            message: e.to_string(),
88        })?;
89        // Gemini's matcher narrows to run_shell_command in config, but
90        // some setups may dispatch all tools through the same hook.
91        // For non-shell tools, return Err so the runtime exits 0
92        // silently — equivalent to "no opinion" — and Gemini falls
93        // back to its own permission rules.
94        if let Some(name) = &envelope.tool_name
95            && name != "run_shell_command"
96            && name != "Shell"
97        {
98            return Err(ParseError {
99                message: format!("not a shell tool: {name}"),
100            });
101        }
102        Ok(HookInput {
103            command: envelope.tool_input.command,
104            cwd: envelope.cwd,
105            root: super::env_root("GEMINI_PROJECT_DIR"),
106        })
107    }
108
109    fn render_response(&self, verdict: Verdict) -> HookResponse {
110        if verdict.is_allowed() {
111            let reason = allow_reason(verdict);
112            // Gemini contract: `decision` (not permission /
113            // permissionDecision). Values: "allow" or "deny" only —
114            // no "ask".
115            let body = json!({
116                "decision": "allow",
117                "reason": reason,
118            });
119            HookResponse {
120                stdout: serde_json::to_string(&body).unwrap_or_default(),
121                exit_code: 0,
122            }
123        } else {
124            // Empty stdout is "no opinion" — Gemini's docs note that
125            // exit code drives the outcome and an unparseable stdout
126            // is a warning. Exit 0 + empty body lets Gemini's own
127            // permission system handle it.
128            HookResponse {
129                stdout: String::new(),
130                exit_code: 0,
131            }
132        }
133    }
134}
135
136fn hook_entry(binary: &str) -> Value {
137    json!({
138        "matcher": "^run_shell_command$",
139        "hooks": [{
140            "type": "command",
141            "command": binary,
142            "timeout": 60_000,
143        }]
144    })
145}
146
147fn has_safe_chains_hook(settings: &Value) -> bool {
148    settings
149        .get("hooks")
150        .and_then(|h| h.get("BeforeTool"))
151        .and_then(|arr| arr.as_array())
152        .is_some_and(|entries| {
153            entries.iter().any(|entry| {
154                entry
155                    .get("hooks")
156                    .and_then(|h| h.as_array())
157                    .is_some_and(|hooks| {
158                        hooks.iter().any(|hook| {
159                            hook.get("command")
160                                .and_then(|c| c.as_str())
161                                .is_some_and(|cmd| cmd.contains("safe-chains"))
162                        })
163                    })
164            })
165        })
166}
167
168fn add_hook(settings: &mut Value, binary: &str) {
169    if !settings.is_object() {
170        *settings = json!({});
171    }
172    let Some(obj) = settings.as_object_mut() else {
173        unreachable!("settings was just set to an object");
174    };
175    let hooks = obj
176        .entry("hooks")
177        .or_insert_with(|| json!({}))
178        .as_object_mut()
179        .expect("hooks key was created above as an object");
180    let before_tool = hooks
181        .entry("BeforeTool")
182        .or_insert_with(|| json!([]))
183        .as_array_mut()
184        .expect("BeforeTool was created above as an array");
185    before_tool.push(hook_entry(binary));
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191    use crate::verdict::SafetyLevel;
192
193    fn target() -> GeminiTarget {
194        GeminiTarget
195    }
196
197    /// Verbatim shape from the Gemini CLI hooks reference. The bash
198    /// command lives in tool_input.command, matched by tool_name.
199    const GEMINI_DOCS_SAMPLE: &str = r#"{
200        "session_id": "abc123",
201        "transcript_path": "/Users/me/.gemini/transcripts/abc.json",
202        "cwd": "/Users/me/project",
203        "hook_event_name": "BeforeTool",
204        "timestamp": "2026-05-06T12:00:00Z",
205        "tool_name": "run_shell_command",
206        "tool_input": {"command": "ls -la"}
207    }"#;
208
209    #[test]
210    fn install_no_gemini_dir_skips() {
211        let dir = tempfile::tempdir().unwrap();
212        let outcome = target().install(dir.path()).unwrap();
213        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
214    }
215
216    #[test]
217    fn install_creates_settings_file() {
218        let dir = tempfile::tempdir().unwrap();
219        std::fs::create_dir(dir.path().join(".gemini")).unwrap();
220        let outcome = target().install(dir.path()).unwrap();
221        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
222        let contents = std::fs::read_to_string(dir.path().join(".gemini/settings.json")).unwrap();
223        let settings: Value = serde_json::from_str(&contents).unwrap();
224        assert!(has_safe_chains_hook(&settings));
225    }
226
227    #[test]
228    fn install_uses_subcommand_invocation() {
229        let dir = tempfile::tempdir().unwrap();
230        std::fs::create_dir(dir.path().join(".gemini")).unwrap();
231        target().install(dir.path()).unwrap();
232        let contents = std::fs::read_to_string(dir.path().join(".gemini/settings.json")).unwrap();
233        assert!(contents.contains("safe-chains hook gemini"));
234    }
235
236    #[test]
237    fn install_idempotent() {
238        let dir = tempfile::tempdir().unwrap();
239        std::fs::create_dir(dir.path().join(".gemini")).unwrap();
240        target().install(dir.path()).unwrap();
241        let outcome = target().install(dir.path()).unwrap();
242        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
243    }
244
245    #[test]
246    fn parse_input_extracts_command_from_tool_input() {
247        let parsed = GeminiHookFormat.parse_input(GEMINI_DOCS_SAMPLE).unwrap();
248        assert_eq!(parsed.command, "ls -la");
249        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project"));
250    }
251
252    #[test]
253    fn parse_input_skips_non_shell_tool_names() {
254        // If the matcher in config doesn't narrow to run_shell_command,
255        // a non-shell tool may dispatch through. We return Err so the
256        // runtime exits silently — Gemini falls back to its own perms.
257        let stdin = r#"{"tool_name": "list_files", "tool_input": {"command": "ignored"}}"#;
258        assert!(GeminiHookFormat.parse_input(stdin).is_err());
259    }
260
261    #[test]
262    fn parse_input_rejects_garbage() {
263        assert!(GeminiHookFormat.parse_input("not json").is_err());
264        assert!(GeminiHookFormat.parse_input("{}").is_err());
265    }
266
267    #[test]
268    fn render_response_uses_decision_key_not_permission() {
269        // Gemini contract is `decision`, NOT `permission` /
270        // `permissionDecision`. Wiring this wrong silently fails the
271        // hook (warning, action proceeds) rather than blocking.
272        let r = GeminiHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
273        let v: Value = serde_json::from_str(&r.stdout).unwrap();
274        assert_eq!(v.get("decision").and_then(|s| s.as_str()), Some("allow"));
275        assert!(v.get("permission").is_none());
276        assert!(v.get("permissionDecision").is_none());
277    }
278
279    #[test]
280    fn render_response_includes_reason() {
281        let r = GeminiHookFormat.render_response(Verdict::Allowed(SafetyLevel::SafeWrite));
282        let v: Value = serde_json::from_str(&r.stdout).unwrap();
283        assert!(v.get("reason").and_then(|s| s.as_str()).is_some());
284    }
285
286    #[test]
287    fn render_response_deny_emits_empty_body() {
288        let r = GeminiHookFormat.render_response(Verdict::Denied);
289        assert_eq!(r.stdout, "");
290    }
291
292    #[test]
293    fn install_uses_correct_matcher() {
294        // Gemini's matcher is regex on tool name; `^run_shell_command$`
295        // is the canonical shell-tool matcher.
296        let dir = tempfile::tempdir().unwrap();
297        std::fs::create_dir(dir.path().join(".gemini")).unwrap();
298        target().install(dir.path()).unwrap();
299        let contents = std::fs::read_to_string(dir.path().join(".gemini/settings.json")).unwrap();
300        assert!(contents.contains("run_shell_command"));
301    }
302}