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