Skip to main content

safe_chains/targets/
copilot.rs

1use 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" // lowercase — Copilot's tool name, not Claude's `Bash`
22    }
23
24    #[cfg(test)]
25    fn sample_envelope(&self, tool: &str, command: &str) -> Option<String> {
26        // `toolArgs` is a nested JSON STRING, not an object.
27        Some(format!(r#"{{"toolName":"{tool}","toolArgs":"{{\"command\":\"{command}\"}}"}}"#))
28    }
29
30    fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
31        // Copilot reads hooks from per-repo `<repo>/.github/hooks/*.json` OR the user-global
32        // `~/.copilot/hooks/` (or `$COPILOT_HOME/hooks/`); upstream's hooks-configuration docs say
33        // both are loaded and all entries run. We install to the user-global dir; a per-repo install
34        // would need a project path. The live drive (v1.0.71) fired the per-repo `.github/hooks/`
35        // config and confirmed `~/.copilot/` is the real config root — the earlier `~/.github/hooks/`
36        // guess was wrong and never fired.
37        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    /// `install`'s body with the hook binary's path injected: the real install passes the
52    /// canonicalized `current_exe` (falling back to the bare invocation when discovery fails),
53    /// while the tests pass a fixed path — under `cargo test` the running binary is
54    /// `safe_chains-<hash>`, which `has_safe_chains_hook` only recognizes when some directory in
55    /// the checkout's path is literally named "safe-chains".
56    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        // Copilot's quirk: toolArgs is a JSON-encoded *string*, not a
102        // nested object. We must parse the outer envelope, then parse
103        // the toolArgs string a second time to recover {command}.
104        let envelope: CopilotHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
105
106        // The hook fires for every tool by default — Copilot's config
107        // has no matcher. Self-filter to the bash tool here; for other
108        // tools, return Err so the runtime exits silently and Copilot
109        // falls back to its own permission rules.
110        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            cwd_declared: false,
122            root: None, // copilot sends cwd but no documented project root
123            // No scratchpad layout researched for this harness yet (see docs/design/agent-scratchpad.md).
124            session_id: None,
125            permission_mode: None,
126        })
127    }
128
129    fn decision_pointer(&self) -> &'static str {
130        "/permissionDecision" // FLAT, not nested — same leaf name as Claude
131    }
132
133    fn render_response(&self, verdict: Verdict) -> HookResponse {
134        // Copilot honors BOTH `allow` and `deny` — VERIFIED LIVE (v1.0.71): a hook `allow` auto-runs
135        // the command and even suppresses copilot's own directory-access prompt; a hook `deny` blocks
136        // it and surfaces our `permissionDecisionReason`. (The earlier "only deny is processed" note
137        // is stale.) So a safe command gets `allow` (a real grant) and a gated one ABSTAINS (empty),
138        // deferring to copilot's own per-command prompt — copilot has interactive review, so we don't
139        // hard-deny. Copilot's response is a FLAT object (no `hookSpecificOutput` wrapper).
140        if verdict.is_allowed() {
141            let reason = allow_reason(verdict);
142            let body = json!({
143                "permissionDecision": "allow",
144                "permissionDecisionReason": reason,
145            });
146            HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
147        } else {
148            HookResponse { stdout: String::new(), exit_code: 0 }
149        }
150    }
151}
152
153fn build_settings(exe: Option<&Path>) -> Value {
154    // Copilot's config: flat object with `version` and `hooks.preToolUse[]`.
155    // No `matcher` in entries — script self-filters on `toolName`. Field
156    // name is `bash` (the script path), NOT `command`. `None` means the
157    // binary's path is unknown — the bare invocation Copilot resolves itself.
158    let resolved = exe
159        .map(|p| format!("{} hook copilot", p.display()))
160        .unwrap_or_else(|| "safe-chains hook copilot".to_string());
161    json!({
162        "version": 1,
163        "hooks": {
164            "preToolUse": [
165                {
166                    "type": "command",
167                    "bash": resolved,
168                    "comment": "safe-chains: validate every Bash tool call before it runs.",
169                    "timeoutSec": 60,
170                }
171            ]
172        }
173    })
174}
175
176fn has_safe_chains_hook(settings: &Value) -> bool {
177    settings.pointer("/hooks/preToolUse").and_then(|arr| arr.as_array()).is_some_and(|entries| {
178        entries
179            .iter()
180            .any(|entry| entry.get("bash").and_then(|c| c.as_str()).is_some_and(|cmd| cmd.contains("safe-chains")))
181    })
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187    use crate::verdict::SafetyLevel;
188
189    fn target() -> CopilotTarget {
190        CopilotTarget
191    }
192
193    /// Fixed hook-binary path for the install tests, so they pass wherever the checkout lives:
194    /// under `cargo test` the running binary is `safe_chains-<hash>`, which `has_safe_chains_hook`
195    /// only recognizes when some directory in the checkout's path is literally named
196    /// "safe-chains".
197    const EXE: &str = "/opt/homebrew/bin/safe-chains";
198
199    /// Verbatim shape from docs.github.com/en/copilot/reference/
200    /// hooks-configuration. The `toolArgs` field is a JSON-encoded
201    /// STRING, not a nested object — must be parsed twice.
202    const COPILOT_DOCS_SAMPLE: &str = r#"{
203        "timestamp": 1704614600000,
204        "cwd": "/path/to/project",
205        "toolName": "bash",
206        "toolArgs": "{\"command\":\"ls -la\",\"description\":\"list files\"}"
207    }"#;
208
209    #[test]
210    fn install_creates_hooks_file() {
211        let dir = tempfile::tempdir().unwrap();
212        let outcome = target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
213        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
214        let path = dir.path().join(".copilot/hooks/safe-chains.json");
215        assert!(path.exists());
216        let contents = std::fs::read_to_string(&path).unwrap();
217        let settings: Value = serde_json::from_str(&contents).unwrap();
218        assert!(has_safe_chains_hook(&settings));
219    }
220
221    #[test]
222    fn install_uses_bash_field_not_command() {
223        // Copilot's script-path field is `bash`, not `command`. Wiring
224        // this to `command` would silently mis-configure the hook.
225        let dir = tempfile::tempdir().unwrap();
226        target().install(dir.path()).unwrap();
227        let contents = std::fs::read_to_string(dir.path().join(".copilot/hooks/safe-chains.json")).unwrap();
228        let settings: Value = serde_json::from_str(&contents).unwrap();
229        let entry = settings.pointer("/hooks/preToolUse/0").unwrap();
230        assert!(entry.get("bash").is_some(), "must use `bash` key");
231        assert!(entry.get("command").is_none(), "must NOT use `command` key");
232    }
233
234    #[test]
235    fn install_uses_subcommand_invocation() {
236        let dir = tempfile::tempdir().unwrap();
237        target().install(dir.path()).unwrap();
238        let contents = std::fs::read_to_string(dir.path().join(".copilot/hooks/safe-chains.json")).unwrap();
239        assert!(contents.contains("hook copilot"));
240    }
241
242    #[test]
243    fn install_idempotent() {
244        let dir = tempfile::tempdir().unwrap();
245        target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
246        let outcome = target().install_with(dir.path(), Some(Path::new(EXE))).unwrap();
247        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
248    }
249
250    #[test]
251    fn install_idempotent_outside_a_safe_chains_directory() {
252        // The regression this file's fix is for: detection must survive a binary path in which no
253        // DIRECTORY is named "safe-chains" — the FILE name alone carries it. Under `cargo test`
254        // the running binary is `safe_chains-<hash>` (underscore), so the real install only
255        // round-tripped when the checkout itself sat inside a "safe-chains" directory.
256        let dir = tempfile::tempdir().unwrap();
257        let exe = Path::new("/usr/local/bin/safe-chains");
258        let first = target().install_with(dir.path(), Some(exe)).unwrap();
259        assert!(matches!(first, InstallOutcome::Installed { .. }));
260        let second = target().install_with(dir.path(), Some(exe)).unwrap();
261        assert!(matches!(second, InstallOutcome::AlreadyConfigured { .. }));
262    }
263
264    #[test]
265    fn parse_input_double_decodes_tool_args() {
266        // The headline quirk: outer JSON, then `toolArgs` is itself a
267        // JSON-encoded string that must be parsed again to recover the
268        // bash command. Tested with the verbatim docs payload.
269        let parsed = CopilotHookFormat.parse_input(COPILOT_DOCS_SAMPLE).unwrap();
270        assert_eq!(parsed.command, "ls -la");
271        assert_eq!(parsed.cwd.as_deref(), Some("/path/to/project"));
272    }
273
274    #[test]
275    fn parse_input_skips_non_bash_tools() {
276        // No matcher in Copilot's config — every tool dispatches
277        // through. Self-filter to "bash"; for others, return Err so
278        // the runtime exits silently and Copilot's own perms apply.
279        let stdin = r#"{
280            "timestamp": 1,
281            "cwd": "/p",
282            "toolName": "edit",
283            "toolArgs": "{\"path\":\"x\"}"
284        }"#;
285        assert!(CopilotHookFormat.parse_input(stdin).is_err());
286    }
287
288    #[test]
289    fn parse_input_rejects_garbage() {
290        assert!(CopilotHookFormat.parse_input("not json").is_err());
291    }
292
293    #[test]
294    fn parse_input_rejects_unparseable_tool_args() {
295        let stdin = r#"{"toolName": "bash", "toolArgs": "not-json"}"#;
296        let result = CopilotHookFormat.parse_input(stdin);
297        assert!(result.is_err());
298    }
299
300    #[test]
301    fn render_response_emits_flat_object_no_wrapper() {
302        // Copilot uses a FLAT response object — no
303        // hookSpecificOutput wrapper key, unlike Claude/Codex/Qwen/
304        // Droid. Wrapping would be silently rejected.
305        let r = CopilotHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
306        let v: Value = serde_json::from_str(&r.stdout).unwrap();
307        assert_eq!(v.get("permissionDecision").and_then(|s| s.as_str()), Some("allow"),);
308        assert!(v.get("hookSpecificOutput").is_none(), "must NOT wrap in hookSpecificOutput",);
309    }
310
311    #[test]
312    fn render_response_includes_reason() {
313        let r = CopilotHookFormat.render_response(Verdict::Allowed(SafetyLevel::SafeWrite));
314        let v: Value = serde_json::from_str(&r.stdout).unwrap();
315        assert!(v.get("permissionDecisionReason").and_then(|s| s.as_str()).is_some());
316    }
317
318    #[test]
319    fn render_response_deny_emits_empty_body() {
320        let r = CopilotHookFormat.render_response(Verdict::Denied);
321        assert_eq!(r.stdout, "");
322    }
323}