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    #[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 detect_paths(&self, home: &Path) -> Vec<PathBuf> {
26        vec![home.join(".claude")]
27    }
28
29    fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
30        let dir = home.join(".claude");
31        if !dir.exists() {
32            return Ok(InstallOutcome::Skipped { reason: format!("~/.claude not found at {} (Claude Code not installed)", dir.display()) });
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).map_err(|e| format!("Could not read {}: {e}", path.display()))?;
40            let mut settings: Value = serde_json::from_str(&contents).map_err(|e| format!("Could not parse {}: {e}", path.display()))?;
41
42            if has_safe_chains_hook(&settings) {
43                return Ok(InstallOutcome::AlreadyConfigured { path });
44            }
45
46            add_hook(&mut settings, binary)?;
47            let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
48            std::fs::write(&path, format!("{output}\n")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
49            Ok(InstallOutcome::Installed { path })
50        } else {
51            let mut settings = Value::Object(Map::new());
52            add_hook(&mut settings, binary)?;
53            let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
54            std::fs::write(&path, format!("{output}\n")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
55            Ok(InstallOutcome::Installed { path })
56        }
57    }
58
59    fn hook_format(&self) -> Option<&dyn HookFormat> {
60        Some(&ClaudeHookFormat)
61    }
62}
63
64struct ClaudeHookFormat;
65
66#[derive(Deserialize)]
67struct ToolInput {
68    command: String,
69}
70
71#[derive(Deserialize)]
72struct ClaudeHookEnvelope {
73    /// Present in every real envelope; optional so a harness that omits it still works. When it IS
74    /// present and names a different tool, we abstain — see `parse_input`.
75    #[serde(default)]
76    tool_name: Option<String>,
77    tool_input: ToolInput,
78    #[serde(default)]
79    cwd: Option<String>,
80    /// Claude Code's per-session UUID. Used only as the unforgeable anchor for recognizing this
81    /// session's scratchpad (`pathctx::session_scratchpad`); absent → nothing is recognized.
82    #[serde(default)]
83    session_id: Option<String>,
84}
85
86impl HookFormat for ClaudeHookFormat {
87    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
88        let envelope: ClaudeHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
89        // Self-filter on the tool, as gemini/copilot/cursor already do. The configured matcher is
90        // `Bash`, so normally only shell calls arrive — but a hand-edited matcher, or grok
91        // auto-loading `~/.claude/settings.json`, can deliver others, and this target is
92        // ALLOW-capable: emitting `permissionDecision: allow` for a `Read`/`Write`/`Edit` call
93        // grants permission on a tool whose semantics were never analysed. Absent tool_name still
94        // passes, so a harness that omits the field is unaffected.
95        if let Some(name) = &envelope.tool_name
96            && name != "Bash"
97        {
98            return Err(ParseError { message: format!("not a shell tool: {name}") });
99        }
100        Ok(HookInput {
101            command: envelope.tool_input.command,
102            cwd: envelope.cwd,
103            root: super::env_root("CLAUDE_PROJECT_DIR"),
104            session_id: envelope.session_id,
105        })
106    }
107
108    fn decision_pointer(&self) -> &'static str {
109        "/hookSpecificOutput/permissionDecision" // nested under hookSpecificOutput
110    }
111
112    fn render_response(&self, verdict: Verdict) -> HookResponse {
113        if verdict.is_allowed() {
114            let reason = allow_reason(verdict);
115            let body = json!({
116                "hookSpecificOutput": {
117                    "hookEventName": "PreToolUse",
118                    "permissionDecision": "allow",
119                    "permissionDecisionReason": reason,
120                }
121            });
122            HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
123        } else {
124            HookResponse { stdout: String::new(), exit_code: 0 }
125        }
126    }
127
128    fn render_context(&self, context: &str) -> HookResponse {
129        // additionalContext injects model-visible text without a
130        // permissionDecision, so the normal approval flow (and the user's own
131        // allowlist) is untouched.
132        let body = json!({
133            "hookSpecificOutput": {
134                "hookEventName": "PreToolUse",
135                "additionalContext": context,
136            }
137        });
138        HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
139    }
140}
141
142fn hook_entry(binary: &str) -> Value {
143    json!({
144        "matcher": "Bash",
145        "hooks": [{
146            "type": "command",
147            "command": binary,
148        }]
149    })
150}
151
152fn has_safe_chains_hook(settings: &Value) -> bool {
153    settings
154        .get("hooks")
155        .and_then(|h| h.get("PreToolUse"))
156        .and_then(|arr| arr.as_array())
157        .is_some_and(|entries| {
158            entries.iter().any(|entry| {
159                entry.get("hooks").and_then(|h| h.as_array()).is_some_and(|hooks| {
160                    hooks
161                        .iter()
162                        .any(|hook| hook.get("command").and_then(|c| c.as_str()).is_some_and(|cmd| cmd.contains("safe-chains")))
163                })
164            })
165        })
166}
167
168fn add_hook(settings: &mut Value, binary: &str) -> Result<(), String> {
169    super::append_hook_entry(settings, "hooks", "PreToolUse", hook_entry(binary))
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175    use crate::verdict::SafetyLevel;
176
177    fn target() -> ClaudeTarget {
178        ClaudeTarget
179    }
180
181    #[test]
182    fn install_no_claude_dir_skips() {
183        let dir = tempfile::tempdir().unwrap();
184        let outcome = target().install(dir.path()).unwrap();
185        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
186    }
187
188    #[test]
189    fn install_creates_settings_file() {
190        let dir = tempfile::tempdir().unwrap();
191        std::fs::create_dir(dir.path().join(".claude")).unwrap();
192        let outcome = target().install(dir.path()).unwrap();
193        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
194        let contents = std::fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
195        let settings: Value = serde_json::from_str(&contents).unwrap();
196        assert!(has_safe_chains_hook(&settings));
197    }
198
199    #[test]
200    fn install_preserves_existing_settings() {
201        let dir = tempfile::tempdir().unwrap();
202        let claude_dir = dir.path().join(".claude");
203        std::fs::create_dir(&claude_dir).unwrap();
204        std::fs::write(claude_dir.join("settings.json"), r#"{"permissions": {"allow": ["Bash(cargo test *)"]}}"#).unwrap();
205        target().install(dir.path()).unwrap();
206        let contents = std::fs::read_to_string(claude_dir.join("settings.json")).unwrap();
207        let settings: Value = serde_json::from_str(&contents).unwrap();
208        assert!(has_safe_chains_hook(&settings));
209        assert!(settings.get("permissions").and_then(|p| p.get("allow")).is_some(), "existing permissions must be preserved");
210    }
211
212    #[test]
213    fn install_idempotent() {
214        let dir = tempfile::tempdir().unwrap();
215        std::fs::create_dir(dir.path().join(".claude")).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 detect_paths_returns_claude_dir() {
223        let dir = tempfile::tempdir().unwrap();
224        let paths = target().detect_paths(dir.path());
225        assert_eq!(paths, vec![dir.path().join(".claude")]);
226    }
227
228    #[test]
229    fn parse_input_extracts_command() {
230        let stdin = r#"{"tool_input": {"command": "ls -la"}, "cwd": "/tmp"}"#;
231        let parsed = ClaudeHookFormat.parse_input(stdin).unwrap();
232        assert_eq!(parsed.command, "ls -la");
233        assert_eq!(parsed.cwd.as_deref(), Some("/tmp"));
234    }
235
236    #[test]
237    fn parse_input_rejects_garbage() {
238        assert!(ClaudeHookFormat.parse_input("not json").is_err());
239        assert!(ClaudeHookFormat.parse_input("{}").is_err());
240    }
241
242    #[test]
243    fn render_response_allow_emits_allow_envelope() {
244        let r = ClaudeHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
245        assert_eq!(r.exit_code, 0);
246        let v: Value = serde_json::from_str(&r.stdout).unwrap();
247        assert_eq!(v.pointer("/hookSpecificOutput/permissionDecision").and_then(|d| d.as_str()), Some("allow"),);
248    }
249
250    #[test]
251    fn render_response_deny_emits_empty_body() {
252        let r = ClaudeHookFormat.render_response(Verdict::Denied);
253        assert_eq!(r.exit_code, 0);
254        assert_eq!(r.stdout, "");
255    }
256
257    #[test]
258    fn render_context_injects_additional_context_without_decision() {
259        let r = ClaudeHookFormat.render_context("hello model");
260        assert_eq!(r.exit_code, 0);
261        let v: Value = serde_json::from_str(&r.stdout).unwrap();
262        assert_eq!(v.pointer("/hookSpecificOutput/additionalContext").and_then(|c| c.as_str()), Some("hello model"),);
263        // Crucial: no permissionDecision, so the user's allowlist/flow is untouched.
264        assert!(v.pointer("/hookSpecificOutput/permissionDecision").is_none());
265    }
266
267    #[test]
268    fn render_response_safewrite_carries_appropriate_reason() {
269        let r = ClaudeHookFormat.render_response(Verdict::Allowed(SafetyLevel::SafeWrite));
270        let v: Value = serde_json::from_str(&r.stdout).unwrap();
271        assert_eq!(
272            v.pointer("/hookSpecificOutput/permissionDecisionReason").and_then(|s| s.as_str()),
273            Some(allow_reason(Verdict::Allowed(SafetyLevel::SafeWrite))),
274        );
275    }
276}