safe_chains/targets/
copilot.rs1use std::path::{Path, PathBuf};
2
3use serde::Deserialize;
4use serde_json::{Value, json};
5
6use super::{HookFormat, HookInput, HookResponse, InstallOutcome, ParseError, Target, allow_reason};
7use crate::verdict::Verdict;
8
9pub struct CopilotTarget;
10
11impl Target for CopilotTarget {
12 fn name(&self) -> &'static str {
13 "copilot"
14 }
15
16 fn display_name(&self) -> &'static str {
17 "GitHub Copilot CLI"
18 }
19
20 fn shell_tool_name(&self) -> &'static str {
21 "bash" }
23
24 #[cfg(test)]
25 fn sample_envelope(&self, tool: &str, command: &str) -> Option<String> {
26 Some(format!(r#"{{"toolName":"{tool}","toolArgs":"{{\"command\":\"{command}\"}}"}}"#))
28 }
29
30 fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
31 vec![home.join(".copilot").join("hooks")]
38 }
39
40 fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
41 let exe = std::env::current_exe().ok().and_then(|p| p.canonicalize().ok());
42 self.install_with(home, exe.as_deref())
43 }
44
45 fn hook_format(&self) -> Option<&dyn HookFormat> {
46 Some(&CopilotHookFormat)
47 }
48}
49
50impl CopilotTarget {
51 fn install_with(&self, home: &Path, exe: Option<&Path>) -> Result<InstallOutcome, String> {
57 let dir = home.join(".copilot").join("hooks");
58 if let Err(e) = std::fs::create_dir_all(&dir) {
59 return Err(format!("Could not create {}: {e}", dir.display()));
60 }
61
62 let path = dir.join("safe-chains.json");
63
64 if path.exists() {
65 let contents = std::fs::read_to_string(&path).map_err(|e| format!("Could not read {}: {e}", path.display()))?;
66 let settings: Value = serde_json::from_str(&contents).map_err(|e| format!("Could not parse {}: {e}", path.display()))?;
67 if has_safe_chains_hook(&settings) {
68 return Ok(InstallOutcome::AlreadyConfigured { path });
69 }
70 }
71
72 let settings = build_settings(exe);
73 let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
74 std::fs::write(&path, format!("{output}\n")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
75 Ok(InstallOutcome::Installed { path })
76 }
77}
78
79struct CopilotHookFormat;
80
81#[derive(Deserialize)]
82struct CopilotHookEnvelope {
83 #[serde(default)]
84 #[serde(rename = "toolName")]
85 tool_name: Option<String>,
86 #[serde(default)]
87 #[serde(rename = "toolArgs")]
88 tool_args: Option<String>,
89 #[serde(default)]
90 cwd: Option<String>,
91}
92
93#[derive(Deserialize)]
94struct CopilotToolArgs {
95 #[serde(default)]
96 command: Option<String>,
97}
98
99impl HookFormat for CopilotHookFormat {
100 fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
101 let envelope: CopilotHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
105
106 let is_bash_tool = envelope.tool_name.as_deref().is_some_and(|n| n == "bash");
111 if !is_bash_tool {
112 return Err(ParseError { message: format!("not a bash tool: {:?}", envelope.tool_name.as_deref().unwrap_or("<missing>")) });
113 }
114
115 let raw_args = envelope.tool_args.unwrap_or_default();
116 let inner: CopilotToolArgs =
117 serde_json::from_str(&raw_args).map_err(|e| ParseError { message: format!("toolArgs not a parseable JSON string: {e}") })?;
118 Ok(HookInput {
119 command: inner.command.unwrap_or_default(),
120 cwd: envelope.cwd,
121 root: None, session_id: None,
124 permission_mode: None,
125 })
126 }
127
128 fn decision_pointer(&self) -> &'static str {
129 "/permissionDecision" }
131
132 fn render_response(&self, verdict: Verdict) -> HookResponse {
133 if verdict.is_allowed() {
140 let reason = allow_reason(verdict);
141 let body = json!({
142 "permissionDecision": "allow",
143 "permissionDecisionReason": reason,
144 });
145 HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
146 } else {
147 HookResponse { stdout: String::new(), exit_code: 0 }
148 }
149 }
150}
151
152fn build_settings(exe: Option<&Path>) -> Value {
153 let resolved = exe
158 .map(|p| format!("{} hook copilot", p.display()))
159 .unwrap_or_else(|| "safe-chains hook copilot".to_string());
160 json!({
161 "version": 1,
162 "hooks": {
163 "preToolUse": [
164 {
165 "type": "command",
166 "bash": resolved,
167 "comment": "safe-chains: validate every Bash tool call before it runs.",
168 "timeoutSec": 60,
169 }
170 ]
171 }
172 })
173}
174
175fn has_safe_chains_hook(settings: &Value) -> bool {
176 settings.pointer("/hooks/preToolUse").and_then(|arr| arr.as_array()).is_some_and(|entries| {
177 entries
178 .iter()
179 .any(|entry| entry.get("bash").and_then(|c| c.as_str()).is_some_and(|cmd| cmd.contains("safe-chains")))
180 })
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186 use crate::verdict::SafetyLevel;
187
188 fn target() -> CopilotTarget {
189 CopilotTarget
190 }
191
192 const EXE: &str = "/opt/homebrew/bin/safe-chains";
197
198 const COPILOT_DOCS_SAMPLE: &str = r#"{
202 "timestamp": 1704614600000,
203 "cwd": "/path/to/project",
204 "toolName": "bash",
205 "toolArgs": "{\"command\":\"ls -la\",\"description\":\"list files\"}"
206 }"#;
207
208 #[test]
209 fn install_creates_hooks_file() {
210 let dir = tempfile::tempdir().unwrap();
211 let outcome = target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
212 assert!(matches!(outcome, InstallOutcome::Installed { .. }));
213 let path = dir.path().join(".copilot/hooks/safe-chains.json");
214 assert!(path.exists());
215 let contents = std::fs::read_to_string(&path).unwrap();
216 let settings: Value = serde_json::from_str(&contents).unwrap();
217 assert!(has_safe_chains_hook(&settings));
218 }
219
220 #[test]
221 fn install_uses_bash_field_not_command() {
222 let dir = tempfile::tempdir().unwrap();
225 target().install(dir.path()).unwrap();
226 let contents = std::fs::read_to_string(dir.path().join(".copilot/hooks/safe-chains.json")).unwrap();
227 let settings: Value = serde_json::from_str(&contents).unwrap();
228 let entry = settings.pointer("/hooks/preToolUse/0").unwrap();
229 assert!(entry.get("bash").is_some(), "must use `bash` key");
230 assert!(entry.get("command").is_none(), "must NOT use `command` key");
231 }
232
233 #[test]
234 fn install_uses_subcommand_invocation() {
235 let dir = tempfile::tempdir().unwrap();
236 target().install(dir.path()).unwrap();
237 let contents = std::fs::read_to_string(dir.path().join(".copilot/hooks/safe-chains.json")).unwrap();
238 assert!(contents.contains("hook copilot"));
239 }
240
241 #[test]
242 fn install_idempotent() {
243 let dir = tempfile::tempdir().unwrap();
244 target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
245 let outcome = target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
246 assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
247 }
248
249 #[test]
250 fn install_idempotent_outside_a_safe_chains_directory() {
251 let dir = tempfile::tempdir().unwrap();
256 let exe = Path::new("/usr/local/bin/safe-chains");
257 let first = target().install_with(dir.path(), Some(exe)).unwrap();
258 assert!(matches!(first, InstallOutcome::Installed { .. }));
259 let second = target().install_with(dir.path(), Some(exe)).unwrap();
260 assert!(matches!(second, InstallOutcome::AlreadyConfigured { .. }));
261 }
262
263 #[test]
264 fn parse_input_double_decodes_tool_args() {
265 let parsed = CopilotHookFormat.parse_input(COPILOT_DOCS_SAMPLE).unwrap();
269 assert_eq!(parsed.command, "ls -la");
270 assert_eq!(parsed.cwd.as_deref(), Some("/path/to/project"));
271 }
272
273 #[test]
274 fn parse_input_skips_non_bash_tools() {
275 let stdin = r#"{
279 "timestamp": 1,
280 "cwd": "/p",
281 "toolName": "edit",
282 "toolArgs": "{\"path\":\"x\"}"
283 }"#;
284 assert!(CopilotHookFormat.parse_input(stdin).is_err());
285 }
286
287 #[test]
288 fn parse_input_rejects_garbage() {
289 assert!(CopilotHookFormat.parse_input("not json").is_err());
290 }
291
292 #[test]
293 fn parse_input_rejects_unparseable_tool_args() {
294 let stdin = r#"{"toolName": "bash", "toolArgs": "not-json"}"#;
295 let result = CopilotHookFormat.parse_input(stdin);
296 assert!(result.is_err());
297 }
298
299 #[test]
300 fn render_response_emits_flat_object_no_wrapper() {
301 let r = CopilotHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
305 let v: Value = serde_json::from_str(&r.stdout).unwrap();
306 assert_eq!(v.get("permissionDecision").and_then(|s| s.as_str()), Some("allow"),);
307 assert!(v.get("hookSpecificOutput").is_none(), "must NOT wrap in hookSpecificOutput",);
308 }
309
310 #[test]
311 fn render_response_includes_reason() {
312 let r = CopilotHookFormat.render_response(Verdict::Allowed(SafetyLevel::SafeWrite));
313 let v: Value = serde_json::from_str(&r.stdout).unwrap();
314 assert!(v.get("permissionDecisionReason").and_then(|s| s.as_str()).is_some());
315 }
316
317 #[test]
318 fn render_response_deny_emits_empty_body() {
319 let r = CopilotHookFormat.render_response(Verdict::Denied);
320 assert_eq!(r.stdout, "");
321 }
322}