Skip to main content

safe_chains/targets/
claude.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 ClaudeTarget;
10
11impl Target for ClaudeTarget {
12    fn name(&self) -> &'static str {
13        "claude"
14    }
15
16    fn display_name(&self) -> &'static str {
17        "Claude Code"
18    }
19
20    fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
21        vec![home.join(".claude")]
22    }
23
24    fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
25        let dir = home.join(".claude");
26        if !dir.exists() {
27            return Ok(InstallOutcome::Skipped {
28                reason: format!(
29                    "~/.claude not found at {} (Claude Code not installed)",
30                    dir.display()
31                ),
32            });
33        }
34
35        let path = dir.join("settings.json");
36        let binary = "safe-chains";
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(&ClaudeHookFormat)
65    }
66}
67
68struct ClaudeHookFormat;
69
70#[derive(Deserialize)]
71struct ToolInput {
72    command: String,
73}
74
75#[derive(Deserialize)]
76struct ClaudeHookEnvelope {
77    tool_input: ToolInput,
78    #[serde(default)]
79    cwd: Option<String>,
80}
81
82impl HookFormat for ClaudeHookFormat {
83    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
84        let envelope: ClaudeHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError {
85            message: e.to_string(),
86        })?;
87        Ok(HookInput {
88            command: envelope.tool_input.command,
89            cwd: envelope.cwd,
90        })
91    }
92
93    fn render_response(&self, verdict: Verdict) -> HookResponse {
94        if verdict.is_allowed() {
95            let reason = allow_reason(verdict);
96            let body = json!({
97                "hookSpecificOutput": {
98                    "hookEventName": "PreToolUse",
99                    "permissionDecision": "allow",
100                    "permissionDecisionReason": reason,
101                }
102            });
103            HookResponse {
104                stdout: serde_json::to_string(&body).unwrap_or_default(),
105                exit_code: 0,
106            }
107        } else {
108            HookResponse {
109                stdout: String::new(),
110                exit_code: 0,
111            }
112        }
113    }
114
115    fn render_context(&self, context: &str) -> HookResponse {
116        // additionalContext injects model-visible text without a
117        // permissionDecision, so the normal approval flow (and the user's own
118        // allowlist) is untouched.
119        let body = json!({
120            "hookSpecificOutput": {
121                "hookEventName": "PreToolUse",
122                "additionalContext": context,
123            }
124        });
125        HookResponse {
126            stdout: serde_json::to_string(&body).unwrap_or_default(),
127            exit_code: 0,
128        }
129    }
130}
131
132fn hook_entry(binary: &str) -> Value {
133    json!({
134        "matcher": "Bash",
135        "hooks": [{
136            "type": "command",
137            "command": binary,
138        }]
139    })
140}
141
142fn has_safe_chains_hook(settings: &Value) -> bool {
143    settings
144        .get("hooks")
145        .and_then(|h| h.get("PreToolUse"))
146        .and_then(|arr| arr.as_array())
147        .is_some_and(|entries| {
148            entries.iter().any(|entry| {
149                entry
150                    .get("hooks")
151                    .and_then(|h| h.as_array())
152                    .is_some_and(|hooks| {
153                        hooks.iter().any(|hook| {
154                            hook.get("command")
155                                .and_then(|c| c.as_str())
156                                .is_some_and(|cmd| cmd.contains("safe-chains"))
157                        })
158                    })
159            })
160        })
161}
162
163fn add_hook(settings: &mut Value, binary: &str) {
164    if !settings.is_object() {
165        *settings = json!({});
166    }
167    let Some(obj) = settings.as_object_mut() else {
168        unreachable!("settings was just set to an object");
169    };
170    let hooks = obj
171        .entry("hooks")
172        .or_insert_with(|| json!({}))
173        .as_object_mut()
174        .expect("hooks key was created above as an object");
175    let pre_tool_use = hooks
176        .entry("PreToolUse")
177        .or_insert_with(|| json!([]))
178        .as_array_mut()
179        .expect("PreToolUse key was created above as an array");
180    pre_tool_use.push(hook_entry(binary));
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186    use crate::verdict::SafetyLevel;
187
188    fn target() -> ClaudeTarget {
189        ClaudeTarget
190    }
191
192    #[test]
193    fn install_no_claude_dir_skips() {
194        let dir = tempfile::tempdir().unwrap();
195        let outcome = target().install(dir.path()).unwrap();
196        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
197    }
198
199    #[test]
200    fn install_creates_settings_file() {
201        let dir = tempfile::tempdir().unwrap();
202        std::fs::create_dir(dir.path().join(".claude")).unwrap();
203        let outcome = target().install(dir.path()).unwrap();
204        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
205        let contents =
206            std::fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
207        let settings: Value = serde_json::from_str(&contents).unwrap();
208        assert!(has_safe_chains_hook(&settings));
209    }
210
211    #[test]
212    fn install_preserves_existing_settings() {
213        let dir = tempfile::tempdir().unwrap();
214        let claude_dir = dir.path().join(".claude");
215        std::fs::create_dir(&claude_dir).unwrap();
216        std::fs::write(
217            claude_dir.join("settings.json"),
218            r#"{"permissions": {"allow": ["Bash(cargo test *)"]}}"#,
219        )
220        .unwrap();
221        target().install(dir.path()).unwrap();
222        let contents = std::fs::read_to_string(claude_dir.join("settings.json")).unwrap();
223        let settings: Value = serde_json::from_str(&contents).unwrap();
224        assert!(has_safe_chains_hook(&settings));
225        assert!(
226            settings
227                .get("permissions")
228                .and_then(|p| p.get("allow"))
229                .is_some(),
230            "existing permissions must be preserved"
231        );
232    }
233
234    #[test]
235    fn install_idempotent() {
236        let dir = tempfile::tempdir().unwrap();
237        std::fs::create_dir(dir.path().join(".claude")).unwrap();
238        target().install(dir.path()).unwrap();
239        let outcome = target().install(dir.path()).unwrap();
240        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
241    }
242
243    #[test]
244    fn detect_paths_returns_claude_dir() {
245        let dir = tempfile::tempdir().unwrap();
246        let paths = target().detect_paths(dir.path());
247        assert_eq!(paths, vec![dir.path().join(".claude")]);
248    }
249
250    #[test]
251    fn parse_input_extracts_command() {
252        let stdin = r#"{"tool_input": {"command": "ls -la"}, "cwd": "/tmp"}"#;
253        let parsed = ClaudeHookFormat.parse_input(stdin).unwrap();
254        assert_eq!(parsed.command, "ls -la");
255        assert_eq!(parsed.cwd.as_deref(), Some("/tmp"));
256    }
257
258    #[test]
259    fn parse_input_rejects_garbage() {
260        assert!(ClaudeHookFormat.parse_input("not json").is_err());
261        assert!(ClaudeHookFormat.parse_input("{}").is_err());
262    }
263
264    #[test]
265    fn render_response_allow_emits_allow_envelope() {
266        let r = ClaudeHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
267        assert_eq!(r.exit_code, 0);
268        let v: Value = serde_json::from_str(&r.stdout).unwrap();
269        assert_eq!(
270            v.pointer("/hookSpecificOutput/permissionDecision")
271                .and_then(|d| d.as_str()),
272            Some("allow"),
273        );
274    }
275
276    #[test]
277    fn render_response_deny_emits_empty_body() {
278        let r = ClaudeHookFormat.render_response(Verdict::Denied);
279        assert_eq!(r.exit_code, 0);
280        assert_eq!(r.stdout, "");
281    }
282
283    #[test]
284    fn render_context_injects_additional_context_without_decision() {
285        let r = ClaudeHookFormat.render_context("hello model");
286        assert_eq!(r.exit_code, 0);
287        let v: Value = serde_json::from_str(&r.stdout).unwrap();
288        assert_eq!(
289            v.pointer("/hookSpecificOutput/additionalContext")
290                .and_then(|c| c.as_str()),
291            Some("hello model"),
292        );
293        // Crucial: no permissionDecision, so the user's allowlist/flow is untouched.
294        assert!(v.pointer("/hookSpecificOutput/permissionDecision").is_none());
295    }
296
297    #[test]
298    fn render_response_safewrite_carries_appropriate_reason() {
299        let r = ClaudeHookFormat.render_response(Verdict::Allowed(SafetyLevel::SafeWrite));
300        let v: Value = serde_json::from_str(&r.stdout).unwrap();
301        assert_eq!(
302            v.pointer("/hookSpecificOutput/permissionDecisionReason")
303                .and_then(|s| s.as_str()),
304            Some(allow_reason(Verdict::Allowed(SafetyLevel::SafeWrite))),
305        );
306    }
307}