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