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    /// Where the command runs: absolute, or relative to the workspace root.
74    #[serde(default)]
75    dir_path: Option<String>,
76}
77
78#[derive(Deserialize)]
79struct GeminiHookEnvelope {
80    #[serde(default)]
81    tool_name: Option<String>,
82    tool_input: ToolInput,
83    #[serde(default)]
84    cwd: Option<String>,
85}
86
87impl HookFormat for GeminiHookFormat {
88    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
89        let envelope: GeminiHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
90        // Gemini's matcher narrows to run_shell_command in config, but
91        // some setups may dispatch all tools through the same hook.
92        // For non-shell tools, return Err so the runtime exits 0
93        // silently — equivalent to "no opinion" — and Gemini falls
94        // back to its own permission rules.
95        if let Some(name) = &envelope.tool_name
96            && name != "run_shell_command"
97            && name != "Shell"
98        {
99            return Err(ParseError { message: format!("not a shell tool: {name}") });
100        }
101        let (cwd, cwd_declared) = super::declared_cwd(envelope.cwd, envelope.tool_input.dir_path.as_deref());
102        Ok(HookInput {
103            command: envelope.tool_input.command,
104            cwd,
105            cwd_declared,
106            root: super::env_root("GEMINI_PROJECT_DIR"),
107            // No scratchpad layout researched for this harness yet (see docs/design/agent-scratchpad.md).
108            session_id: None,
109            permission_mode: None,
110        })
111    }
112
113    fn decision_pointer(&self) -> &'static str {
114        "/decision" // not permissionDecision
115    }
116
117    fn render_response(&self, verdict: Verdict) -> HookResponse {
118        if verdict.is_allowed() {
119            let reason = allow_reason(verdict);
120            // Gemini contract: `decision` (not permission /
121            // permissionDecision). Values: "allow" or "deny" only —
122            // no "ask".
123            let body = json!({
124                "decision": "allow",
125                "reason": reason,
126            });
127            HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
128        } else {
129            // Empty stdout is "no opinion" — Gemini's docs note that
130            // exit code drives the outcome and an unparseable stdout
131            // is a warning. Exit 0 + empty body lets Gemini's own
132            // permission system handle it.
133            HookResponse { stdout: String::new(), exit_code: 0 }
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.get("hooks").and_then(|h| h.as_array()).is_some_and(|hooks| {
157                    hooks
158                        .iter()
159                        .any(|hook| hook.get("command").and_then(|c| c.as_str()).is_some_and(|cmd| cmd.contains("safe-chains")))
160                })
161            })
162        })
163}
164
165fn add_hook(settings: &mut Value, binary: &str) -> Result<(), String> {
166    super::append_hook_entry(settings, "hooks", "BeforeTool", hook_entry(binary))
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172    use crate::verdict::SafetyLevel;
173
174    fn target() -> GeminiTarget {
175        GeminiTarget
176    }
177
178    /// Verbatim shape from the Gemini CLI hooks reference. The bash
179    /// command lives in tool_input.command, matched by tool_name.
180    const GEMINI_DOCS_SAMPLE: &str = r#"{
181        "session_id": "abc123",
182        "transcript_path": "/Users/me/.gemini/transcripts/abc.json",
183        "cwd": "/Users/me/project",
184        "hook_event_name": "BeforeTool",
185        "timestamp": "2026-05-06T12:00:00Z",
186        "tool_name": "run_shell_command",
187        "tool_input": {"command": "ls -la"}
188    }"#;
189
190    #[test]
191    fn install_no_gemini_dir_skips() {
192        let dir = tempfile::tempdir().unwrap();
193        let outcome = target().install(dir.path()).unwrap();
194        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
195    }
196
197    #[test]
198    fn install_creates_settings_file() {
199        let dir = tempfile::tempdir().unwrap();
200        std::fs::create_dir(dir.path().join(".gemini")).unwrap();
201        let outcome = target().install(dir.path()).unwrap();
202        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
203        let contents = std::fs::read_to_string(dir.path().join(".gemini/settings.json")).unwrap();
204        let settings: Value = serde_json::from_str(&contents).unwrap();
205        assert!(has_safe_chains_hook(&settings));
206    }
207
208    #[test]
209    fn install_uses_subcommand_invocation() {
210        let dir = tempfile::tempdir().unwrap();
211        std::fs::create_dir(dir.path().join(".gemini")).unwrap();
212        target().install(dir.path()).unwrap();
213        let contents = std::fs::read_to_string(dir.path().join(".gemini/settings.json")).unwrap();
214        assert!(contents.contains("safe-chains hook gemini"));
215    }
216
217    #[test]
218    fn install_idempotent() {
219        let dir = tempfile::tempdir().unwrap();
220        std::fs::create_dir(dir.path().join(".gemini")).unwrap();
221        target().install(dir.path()).unwrap();
222        let outcome = target().install(dir.path()).unwrap();
223        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
224    }
225
226    #[test]
227    fn parse_input_extracts_command_from_tool_input() {
228        let parsed = GeminiHookFormat.parse_input(GEMINI_DOCS_SAMPLE).unwrap();
229        assert_eq!(parsed.command, "ls -la");
230        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project"));
231    }
232
233    #[test]
234    fn parse_input_skips_non_shell_tool_names() {
235        // If the matcher in config doesn't narrow to run_shell_command,
236        // a non-shell tool may dispatch through. We return Err so the
237        // runtime exits silently — Gemini falls back to its own perms.
238        let stdin = r#"{"tool_name": "list_files", "tool_input": {"command": "ignored"}}"#;
239        assert!(GeminiHookFormat.parse_input(stdin).is_err());
240    }
241
242    #[test]
243    fn parse_input_rejects_garbage() {
244        assert!(GeminiHookFormat.parse_input("not json").is_err());
245        assert!(GeminiHookFormat.parse_input("{}").is_err());
246    }
247
248    #[test]
249    fn render_response_uses_decision_key_not_permission() {
250        // Gemini contract is `decision`, NOT `permission` /
251        // `permissionDecision`. Wiring this wrong silently fails the
252        // hook (warning, action proceeds) rather than blocking.
253        let r = GeminiHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
254        let v: Value = serde_json::from_str(&r.stdout).unwrap();
255        assert_eq!(v.get("decision").and_then(|s| s.as_str()), Some("allow"));
256        assert!(v.get("permission").is_none());
257        assert!(v.get("permissionDecision").is_none());
258    }
259
260    #[test]
261    fn render_response_includes_reason() {
262        let r = GeminiHookFormat.render_response(Verdict::Allowed(SafetyLevel::SafeWrite));
263        let v: Value = serde_json::from_str(&r.stdout).unwrap();
264        assert!(v.get("reason").and_then(|s| s.as_str()).is_some());
265    }
266
267    #[test]
268    fn render_response_deny_emits_empty_body() {
269        let r = GeminiHookFormat.render_response(Verdict::Denied);
270        assert_eq!(r.stdout, "");
271    }
272
273    #[test]
274    fn install_uses_correct_matcher() {
275        // Gemini's matcher is regex on tool name; `^run_shell_command$`
276        // is the canonical shell-tool matcher.
277        let dir = tempfile::tempdir().unwrap();
278        std::fs::create_dir(dir.path().join(".gemini")).unwrap();
279        target().install(dir.path()).unwrap();
280        let contents = std::fs::read_to_string(dir.path().join(".gemini/settings.json")).unwrap();
281        assert!(contents.contains("run_shell_command"));
282    }
283}