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