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