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            // No scratchpad layout researched for this harness yet (see docs/design/agent-scratchpad.md).
107            session_id: None,
108        })
109    }
110
111    fn render_response(&self, verdict: Verdict) -> HookResponse {
112        if verdict.is_allowed() {
113            let reason = allow_reason(verdict);
114            // Gemini contract: `decision` (not permission /
115            // permissionDecision). Values: "allow" or "deny" only —
116            // no "ask".
117            let body = json!({
118                "decision": "allow",
119                "reason": reason,
120            });
121            HookResponse {
122                stdout: serde_json::to_string(&body).unwrap_or_default(),
123                exit_code: 0,
124            }
125        } else {
126            // Empty stdout is "no opinion" — Gemini's docs note that
127            // exit code drives the outcome and an unparseable stdout
128            // is a warning. Exit 0 + empty body lets Gemini's own
129            // permission system handle it.
130            HookResponse {
131                stdout: String::new(),
132                exit_code: 0,
133            }
134        }
135    }
136}
137
138fn hook_entry(binary: &str) -> Value {
139    json!({
140        "matcher": "^run_shell_command$",
141        "hooks": [{
142            "type": "command",
143            "command": binary,
144            "timeout": 60_000,
145        }]
146    })
147}
148
149fn has_safe_chains_hook(settings: &Value) -> bool {
150    settings
151        .get("hooks")
152        .and_then(|h| h.get("BeforeTool"))
153        .and_then(|arr| arr.as_array())
154        .is_some_and(|entries| {
155            entries.iter().any(|entry| {
156                entry
157                    .get("hooks")
158                    .and_then(|h| h.as_array())
159                    .is_some_and(|hooks| {
160                        hooks.iter().any(|hook| {
161                            hook.get("command")
162                                .and_then(|c| c.as_str())
163                                .is_some_and(|cmd| cmd.contains("safe-chains"))
164                        })
165                    })
166            })
167        })
168}
169
170fn add_hook(settings: &mut Value, binary: &str) {
171    if !settings.is_object() {
172        *settings = json!({});
173    }
174    let Some(obj) = settings.as_object_mut() else {
175        unreachable!("settings was just set to an object");
176    };
177    let hooks = obj
178        .entry("hooks")
179        .or_insert_with(|| json!({}))
180        .as_object_mut()
181        .expect("hooks key was created above as an object");
182    let before_tool = hooks
183        .entry("BeforeTool")
184        .or_insert_with(|| json!([]))
185        .as_array_mut()
186        .expect("BeforeTool was created above as an array");
187    before_tool.push(hook_entry(binary));
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193    use crate::verdict::SafetyLevel;
194
195    fn target() -> GeminiTarget {
196        GeminiTarget
197    }
198
199    /// Verbatim shape from the Gemini CLI hooks reference. The bash
200    /// command lives in tool_input.command, matched by tool_name.
201    const GEMINI_DOCS_SAMPLE: &str = r#"{
202        "session_id": "abc123",
203        "transcript_path": "/Users/me/.gemini/transcripts/abc.json",
204        "cwd": "/Users/me/project",
205        "hook_event_name": "BeforeTool",
206        "timestamp": "2026-05-06T12:00:00Z",
207        "tool_name": "run_shell_command",
208        "tool_input": {"command": "ls -la"}
209    }"#;
210
211    #[test]
212    fn install_no_gemini_dir_skips() {
213        let dir = tempfile::tempdir().unwrap();
214        let outcome = target().install(dir.path()).unwrap();
215        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
216    }
217
218    #[test]
219    fn install_creates_settings_file() {
220        let dir = tempfile::tempdir().unwrap();
221        std::fs::create_dir(dir.path().join(".gemini")).unwrap();
222        let outcome = target().install(dir.path()).unwrap();
223        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
224        let contents = std::fs::read_to_string(dir.path().join(".gemini/settings.json")).unwrap();
225        let settings: Value = serde_json::from_str(&contents).unwrap();
226        assert!(has_safe_chains_hook(&settings));
227    }
228
229    #[test]
230    fn install_uses_subcommand_invocation() {
231        let dir = tempfile::tempdir().unwrap();
232        std::fs::create_dir(dir.path().join(".gemini")).unwrap();
233        target().install(dir.path()).unwrap();
234        let contents = std::fs::read_to_string(dir.path().join(".gemini/settings.json")).unwrap();
235        assert!(contents.contains("safe-chains hook gemini"));
236    }
237
238    #[test]
239    fn install_idempotent() {
240        let dir = tempfile::tempdir().unwrap();
241        std::fs::create_dir(dir.path().join(".gemini")).unwrap();
242        target().install(dir.path()).unwrap();
243        let outcome = target().install(dir.path()).unwrap();
244        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
245    }
246
247    #[test]
248    fn parse_input_extracts_command_from_tool_input() {
249        let parsed = GeminiHookFormat.parse_input(GEMINI_DOCS_SAMPLE).unwrap();
250        assert_eq!(parsed.command, "ls -la");
251        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project"));
252    }
253
254    #[test]
255    fn parse_input_skips_non_shell_tool_names() {
256        // If the matcher in config doesn't narrow to run_shell_command,
257        // a non-shell tool may dispatch through. We return Err so the
258        // runtime exits silently — Gemini falls back to its own perms.
259        let stdin = r#"{"tool_name": "list_files", "tool_input": {"command": "ignored"}}"#;
260        assert!(GeminiHookFormat.parse_input(stdin).is_err());
261    }
262
263    #[test]
264    fn parse_input_rejects_garbage() {
265        assert!(GeminiHookFormat.parse_input("not json").is_err());
266        assert!(GeminiHookFormat.parse_input("{}").is_err());
267    }
268
269    #[test]
270    fn render_response_uses_decision_key_not_permission() {
271        // Gemini contract is `decision`, NOT `permission` /
272        // `permissionDecision`. Wiring this wrong silently fails the
273        // hook (warning, action proceeds) rather than blocking.
274        let r = GeminiHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
275        let v: Value = serde_json::from_str(&r.stdout).unwrap();
276        assert_eq!(v.get("decision").and_then(|s| s.as_str()), Some("allow"));
277        assert!(v.get("permission").is_none());
278        assert!(v.get("permissionDecision").is_none());
279    }
280
281    #[test]
282    fn render_response_includes_reason() {
283        let r = GeminiHookFormat.render_response(Verdict::Allowed(SafetyLevel::SafeWrite));
284        let v: Value = serde_json::from_str(&r.stdout).unwrap();
285        assert!(v.get("reason").and_then(|s| s.as_str()).is_some());
286    }
287
288    #[test]
289    fn render_response_deny_emits_empty_body() {
290        let r = GeminiHookFormat.render_response(Verdict::Denied);
291        assert_eq!(r.stdout, "");
292    }
293
294    #[test]
295    fn install_uses_correct_matcher() {
296        // Gemini's matcher is regex on tool name; `^run_shell_command$`
297        // is the canonical shell-tool matcher.
298        let dir = tempfile::tempdir().unwrap();
299        std::fs::create_dir(dir.path().join(".gemini")).unwrap();
300        target().install(dir.path()).unwrap();
301        let contents = std::fs::read_to_string(dir.path().join(".gemini/settings.json")).unwrap();
302        assert!(contents.contains("run_shell_command"));
303    }
304}