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    #[cfg(test)]
21    fn sample_envelope(&self, tool: &str, command: &str) -> Option<String> {
22        Some(format!(r#"{{"tool_name":"{tool}","tool_input":{{"command":"{command}"}}}}"#))
23    }
24
25    fn shell_tool_name(&self) -> &'static str {
26        "run_shell_command"
27    }
28
29    fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
30        vec![home.join(".gemini")]
31    }
32
33    fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
34        let dir = home.join(".gemini");
35        if !dir.exists() {
36            return Ok(InstallOutcome::Skipped { reason: format!("~/.gemini not found at {} (Gemini CLI not installed)", dir.display()) });
37        }
38
39        let path = dir.join("settings.json");
40        let binary = "safe-chains hook gemini";
41
42        if path.exists() {
43            let contents = std::fs::read_to_string(&path).map_err(|e| format!("Could not read {}: {e}", path.display()))?;
44            let mut settings: Value = serde_json::from_str(&contents).map_err(|e| format!("Could not parse {}: {e}", path.display()))?;
45
46            if has_safe_chains_hook(&settings) {
47                return Ok(InstallOutcome::AlreadyConfigured { path });
48            }
49
50            add_hook(&mut settings, binary)?;
51            let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
52            std::fs::write(&path, format!("{output}\n")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
53            Ok(InstallOutcome::Installed { path })
54        } else {
55            let mut settings = Value::Object(Map::new());
56            add_hook(&mut settings, binary)?;
57            let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
58            std::fs::write(&path, format!("{output}\n")).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 { message: e.to_string() })?;
87        // Gemini's matcher narrows to run_shell_command in config, but
88        // some setups may dispatch all tools through the same hook.
89        // For non-shell tools, return Err so the runtime exits 0
90        // silently — equivalent to "no opinion" — and Gemini falls
91        // back to its own permission rules.
92        if let Some(name) = &envelope.tool_name
93            && name != "run_shell_command"
94            && name != "Shell"
95        {
96            return Err(ParseError { message: format!("not a shell tool: {name}") });
97        }
98        Ok(HookInput {
99            command: envelope.tool_input.command,
100            cwd: envelope.cwd,
101            root: super::env_root("GEMINI_PROJECT_DIR"),
102            // No scratchpad layout researched for this harness yet (see docs/design/agent-scratchpad.md).
103            session_id: None,
104            permission_mode: None,
105        })
106    }
107
108    fn decision_pointer(&self) -> &'static str {
109        "/decision" // not permissionDecision
110    }
111
112    fn render_response(&self, verdict: Verdict) -> HookResponse {
113        if verdict.is_allowed() {
114            let reason = allow_reason(verdict);
115            // Gemini contract: `decision` (not permission /
116            // permissionDecision). Values: "allow" or "deny" only —
117            // no "ask".
118            let body = json!({
119                "decision": "allow",
120                "reason": reason,
121            });
122            HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
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 { stdout: String::new(), exit_code: 0 }
129        }
130    }
131}
132
133fn hook_entry(binary: &str) -> Value {
134    json!({
135        "matcher": "^run_shell_command$",
136        "hooks": [{
137            "type": "command",
138            "command": binary,
139            "timeout": 60_000,
140        }]
141    })
142}
143
144fn has_safe_chains_hook(settings: &Value) -> bool {
145    settings
146        .get("hooks")
147        .and_then(|h| h.get("BeforeTool"))
148        .and_then(|arr| arr.as_array())
149        .is_some_and(|entries| {
150            entries.iter().any(|entry| {
151                entry.get("hooks").and_then(|h| h.as_array()).is_some_and(|hooks| {
152                    hooks
153                        .iter()
154                        .any(|hook| hook.get("command").and_then(|c| c.as_str()).is_some_and(|cmd| cmd.contains("safe-chains")))
155                })
156            })
157        })
158}
159
160fn add_hook(settings: &mut Value, binary: &str) -> Result<(), String> {
161    super::append_hook_entry(settings, "hooks", "BeforeTool", hook_entry(binary))
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167    use crate::verdict::SafetyLevel;
168
169    fn target() -> GeminiTarget {
170        GeminiTarget
171    }
172
173    /// Verbatim shape from the Gemini CLI hooks reference. The bash
174    /// command lives in tool_input.command, matched by tool_name.
175    const GEMINI_DOCS_SAMPLE: &str = r#"{
176        "session_id": "abc123",
177        "transcript_path": "/Users/me/.gemini/transcripts/abc.json",
178        "cwd": "/Users/me/project",
179        "hook_event_name": "BeforeTool",
180        "timestamp": "2026-05-06T12:00:00Z",
181        "tool_name": "run_shell_command",
182        "tool_input": {"command": "ls -la"}
183    }"#;
184
185    #[test]
186    fn install_no_gemini_dir_skips() {
187        let dir = tempfile::tempdir().unwrap();
188        let outcome = target().install(dir.path()).unwrap();
189        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
190    }
191
192    #[test]
193    fn install_creates_settings_file() {
194        let dir = tempfile::tempdir().unwrap();
195        std::fs::create_dir(dir.path().join(".gemini")).unwrap();
196        let outcome = target().install(dir.path()).unwrap();
197        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
198        let contents = std::fs::read_to_string(dir.path().join(".gemini/settings.json")).unwrap();
199        let settings: Value = serde_json::from_str(&contents).unwrap();
200        assert!(has_safe_chains_hook(&settings));
201    }
202
203    #[test]
204    fn install_uses_subcommand_invocation() {
205        let dir = tempfile::tempdir().unwrap();
206        std::fs::create_dir(dir.path().join(".gemini")).unwrap();
207        target().install(dir.path()).unwrap();
208        let contents = std::fs::read_to_string(dir.path().join(".gemini/settings.json")).unwrap();
209        assert!(contents.contains("safe-chains hook gemini"));
210    }
211
212    #[test]
213    fn install_idempotent() {
214        let dir = tempfile::tempdir().unwrap();
215        std::fs::create_dir(dir.path().join(".gemini")).unwrap();
216        target().install(dir.path()).unwrap();
217        let outcome = target().install(dir.path()).unwrap();
218        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
219    }
220
221    #[test]
222    fn parse_input_extracts_command_from_tool_input() {
223        let parsed = GeminiHookFormat.parse_input(GEMINI_DOCS_SAMPLE).unwrap();
224        assert_eq!(parsed.command, "ls -la");
225        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project"));
226    }
227
228    #[test]
229    fn parse_input_skips_non_shell_tool_names() {
230        // If the matcher in config doesn't narrow to run_shell_command,
231        // a non-shell tool may dispatch through. We return Err so the
232        // runtime exits silently — Gemini falls back to its own perms.
233        let stdin = r#"{"tool_name": "list_files", "tool_input": {"command": "ignored"}}"#;
234        assert!(GeminiHookFormat.parse_input(stdin).is_err());
235    }
236
237    #[test]
238    fn parse_input_rejects_garbage() {
239        assert!(GeminiHookFormat.parse_input("not json").is_err());
240        assert!(GeminiHookFormat.parse_input("{}").is_err());
241    }
242
243    #[test]
244    fn render_response_uses_decision_key_not_permission() {
245        // Gemini contract is `decision`, NOT `permission` /
246        // `permissionDecision`. Wiring this wrong silently fails the
247        // hook (warning, action proceeds) rather than blocking.
248        let r = GeminiHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
249        let v: Value = serde_json::from_str(&r.stdout).unwrap();
250        assert_eq!(v.get("decision").and_then(|s| s.as_str()), Some("allow"));
251        assert!(v.get("permission").is_none());
252        assert!(v.get("permissionDecision").is_none());
253    }
254
255    #[test]
256    fn render_response_includes_reason() {
257        let r = GeminiHookFormat.render_response(Verdict::Allowed(SafetyLevel::SafeWrite));
258        let v: Value = serde_json::from_str(&r.stdout).unwrap();
259        assert!(v.get("reason").and_then(|s| s.as_str()).is_some());
260    }
261
262    #[test]
263    fn render_response_deny_emits_empty_body() {
264        let r = GeminiHookFormat.render_response(Verdict::Denied);
265        assert_eq!(r.stdout, "");
266    }
267
268    #[test]
269    fn install_uses_correct_matcher() {
270        // Gemini's matcher is regex on tool name; `^run_shell_command$`
271        // is the canonical shell-tool matcher.
272        let dir = tempfile::tempdir().unwrap();
273        std::fs::create_dir(dir.path().join(".gemini")).unwrap();
274        target().install(dir.path()).unwrap();
275        let contents = std::fs::read_to_string(dir.path().join(".gemini/settings.json")).unwrap();
276        assert!(contents.contains("run_shell_command"));
277    }
278}