Skip to main content

safe_chains/targets/
cursor.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 CursorTarget;
10
11impl Target for CursorTarget {
12    fn name(&self) -> &'static str {
13        "cursor"
14    }
15
16    fn display_name(&self) -> &'static str {
17        "Cursor CLI"
18    }
19
20    fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
21        vec![home.join(".cursor")]
22    }
23
24    fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
25        let dir = home.join(".cursor");
26        if !dir.exists() {
27            return Ok(InstallOutcome::Skipped {
28                reason: format!(
29                    "~/.cursor not found at {} (Cursor not installed for this user)",
30                    dir.display()
31                ),
32            });
33        }
34
35        let path = dir.join("hooks.json");
36        let binary = "safe-chains hook cursor";
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 = json!({"version": 1});
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(&CursorHookFormat)
65    }
66}
67
68struct CursorHookFormat;
69
70#[derive(Deserialize)]
71struct CursorHookEnvelope {
72    command: String,
73    #[serde(default)]
74    cwd: Option<String>,
75    #[serde(default)]
76    workspace_roots: Vec<String>,
77}
78
79impl HookFormat for CursorHookFormat {
80    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
81        let mut envelope: CursorHookEnvelope =
82            serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
83        Ok(HookInput {
84            command: envelope.command,
85            cwd: envelope.cwd,
86            // cursor sends the project root(s) in the payload; take the first.
87            root: (!envelope.workspace_roots.is_empty()).then(|| envelope.workspace_roots.swap_remove(0)),
88            // No scratchpad layout researched for this harness yet (see docs/design/agent-scratchpad.md).
89            session_id: None,
90        })
91    }
92
93    fn render_response(&self, verdict: Verdict) -> HookResponse {
94        if verdict.is_allowed() {
95            let reason = allow_reason(verdict);
96            // cursor-agent (v2026.07.16) IGNORES a hook `permission:"allow"` — its own command
97            // allowlist still prompts (a known bug: forum.cursor.com/t/…/144244, HARNESS-BEHAVIORS
98            // §Cursor). We keep emitting it anyway: it is harmless (cursor just prompts, as it would
99            // on silence) and becomes a real grant the moment cursor honors `allow`.
100            let body = json!({
101                "permission": "allow",
102                "agent_message": reason,
103            });
104            HookResponse {
105                stdout: serde_json::to_string(&body).unwrap_or_default(),
106                exit_code: 0,
107            }
108        } else {
109            HookResponse {
110                stdout: String::new(),
111                exit_code: 0,
112            }
113        }
114    }
115
116    // cursor-agent ignores hook `allow` (above) but HONORS `deny` — verified live: a `permission:
117    // "deny"` blocks the command and shows our message. Since `allow` is inert, `deny` is the only
118    // lever that adds protection, so Cursor is a DENY harness (like Codex). Revisit if cursor fixes
119    // `allow`, or if the Cursor IDE differs from the CLI. See HARNESS-BEHAVIORS §Cursor.
120    fn gated_policy(&self) -> super::GatedPolicy {
121        super::GatedPolicy::Deny
122    }
123
124    fn render_deny(&self, reason: &str) -> HookResponse {
125        let body = json!({
126            "permission": "deny",
127            "user_message": reason,
128            "agent_message": reason,
129        });
130        HookResponse {
131            stdout: serde_json::to_string(&body).unwrap_or_default(),
132            exit_code: 0,
133        }
134    }
135}
136
137fn hook_entry(binary: &str) -> Value {
138    json!({
139        "command": binary,
140        "timeout": 30,
141    })
142}
143
144fn has_safe_chains_hook(settings: &Value) -> bool {
145    settings
146        .get("hooks")
147        .and_then(|h| h.get("beforeShellExecution"))
148        .and_then(|arr| arr.as_array())
149        .is_some_and(|entries| {
150            entries.iter().any(|entry| {
151                entry
152                    .get("command")
153                    .and_then(|c| c.as_str())
154                    .is_some_and(|cmd| cmd.contains("safe-chains"))
155            })
156        })
157}
158
159fn add_hook(settings: &mut Value, binary: &str) {
160    if !settings.is_object() {
161        *settings = json!({"version": 1});
162    }
163    let Some(obj) = settings.as_object_mut() else {
164        unreachable!("settings was just set to an object");
165    };
166    if !obj.contains_key("version") {
167        obj.insert("version".to_string(), json!(1));
168    }
169    let hooks = obj
170        .entry("hooks")
171        .or_insert_with(|| json!({}))
172        .as_object_mut()
173        .expect("hooks key was created above as an object");
174    let before_shell = hooks
175        .entry("beforeShellExecution")
176        .or_insert_with(|| json!([]))
177        .as_array_mut()
178        .expect("beforeShellExecution was created above as an array");
179    before_shell.push(hook_entry(binary));
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185    use crate::verdict::SafetyLevel;
186
187    fn target() -> CursorTarget {
188        CursorTarget
189    }
190
191    #[test]
192    fn install_no_cursor_dir_skips() {
193        let dir = tempfile::tempdir().unwrap();
194        let outcome = target().install(dir.path()).unwrap();
195        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
196    }
197
198    #[test]
199    fn install_creates_hooks_file() {
200        let dir = tempfile::tempdir().unwrap();
201        std::fs::create_dir(dir.path().join(".cursor")).unwrap();
202        let outcome = target().install(dir.path()).unwrap();
203        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
204        let contents = std::fs::read_to_string(dir.path().join(".cursor/hooks.json")).unwrap();
205        let settings: Value = serde_json::from_str(&contents).unwrap();
206        assert_eq!(settings.get("version").and_then(|v| v.as_u64()), Some(1));
207        assert!(has_safe_chains_hook(&settings));
208    }
209
210    #[test]
211    fn install_uses_subcommand_invocation() {
212        let dir = tempfile::tempdir().unwrap();
213        std::fs::create_dir(dir.path().join(".cursor")).unwrap();
214        target().install(dir.path()).unwrap();
215        let contents = std::fs::read_to_string(dir.path().join(".cursor/hooks.json")).unwrap();
216        assert!(contents.contains("safe-chains hook cursor"));
217    }
218
219    #[test]
220    fn install_idempotent() {
221        let dir = tempfile::tempdir().unwrap();
222        std::fs::create_dir(dir.path().join(".cursor")).unwrap();
223        target().install(dir.path()).unwrap();
224        let outcome = target().install(dir.path()).unwrap();
225        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
226    }
227
228    #[test]
229    fn install_preserves_existing_hooks() {
230        let dir = tempfile::tempdir().unwrap();
231        let cursor_dir = dir.path().join(".cursor");
232        std::fs::create_dir(&cursor_dir).unwrap();
233        std::fs::write(
234            cursor_dir.join("hooks.json"),
235            r#"{"version": 1, "hooks": {"afterFileEdit": [{"command": "format-it", "timeout": 30}]}}"#,
236        )
237        .unwrap();
238        target().install(dir.path()).unwrap();
239        let contents = std::fs::read_to_string(cursor_dir.join("hooks.json")).unwrap();
240        let settings: Value = serde_json::from_str(&contents).unwrap();
241        assert!(has_safe_chains_hook(&settings));
242        assert!(
243            settings
244                .pointer("/hooks/afterFileEdit")
245                .and_then(|a| a.as_array())
246                .is_some_and(|a| !a.is_empty()),
247            "existing afterFileEdit hook must be preserved"
248        );
249    }
250
251    /// Verbatim sample payload from cursor.com/docs/hooks for the
252    /// `beforeShellExecution` event. Bash command is at top level
253    /// (not nested in tool_input as Claude/Codex do).
254    const CURSOR_DOCS_SAMPLE: &str = r#"{
255        "conversation_id": "abc-123",
256        "generation_id": "gen-456",
257        "model": "claude-sonnet-4-5",
258        "hook_event_name": "beforeShellExecution",
259        "cursor_version": "2.0.43",
260        "workspace_roots": ["/Users/me/project"],
261        "user_email": "me@example.com",
262        "transcript_path": "/Users/me/.cursor/transcripts/abc.json",
263        "command": "ls -la",
264        "cwd": "/Users/me/project",
265        "sandbox": false
266    }"#;
267
268    #[test]
269    fn parse_input_extracts_top_level_command() {
270        let parsed = CursorHookFormat.parse_input(CURSOR_DOCS_SAMPLE).unwrap();
271        assert_eq!(parsed.command, "ls -la");
272        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me/project"));
273    }
274
275    #[test]
276    fn parse_input_rejects_garbage() {
277        assert!(CursorHookFormat.parse_input("not json").is_err());
278        assert!(CursorHookFormat.parse_input("{}").is_err());
279    }
280
281    #[test]
282    fn parse_input_takes_the_project_root_from_workspace_roots() {
283        let stdin = r#"{"command": "ls", "cwd": "/w/p/sub", "workspace_roots": ["/w/p", "/w/other"]}"#;
284        let parsed = CursorHookFormat.parse_input(stdin).unwrap();
285        assert_eq!(parsed.cwd.as_deref(), Some("/w/p/sub"));
286        assert_eq!(parsed.root.as_deref(), Some("/w/p"), "first workspace root");
287        // absent workspace_roots → no root
288        let bare = CursorHookFormat.parse_input(r#"{"command": "ls"}"#).unwrap();
289        assert_eq!(bare.root, None);
290    }
291
292    #[test]
293    fn render_response_uses_permission_key_not_decision() {
294        // Cursor's contract is `permission`, NOT `decision` /
295        // `permissionDecision`. Wiring this wrong is silently fail-
296        // open per their failure semantics — tested explicitly.
297        let r = CursorHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
298        let v: Value = serde_json::from_str(&r.stdout).unwrap();
299        assert_eq!(v.get("permission").and_then(|s| s.as_str()), Some("allow"));
300        assert!(v.get("decision").is_none());
301        assert!(v.get("permissionDecision").is_none());
302    }
303
304    #[test]
305    fn render_response_includes_agent_message() {
306        let r = CursorHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
307        let v: Value = serde_json::from_str(&r.stdout).unwrap();
308        assert!(v.get("agent_message").and_then(|s| s.as_str()).is_some());
309    }
310
311    #[test]
312    fn render_response_deny_emits_empty_body() {
313        // render_response is only called for ALLOWED verdicts; the Denied branch is defensive.
314        let r = CursorHookFormat.render_response(Verdict::Denied);
315        assert_eq!(r.stdout, "");
316    }
317
318    #[test]
319    fn cursor_is_a_deny_harness() {
320        // cursor-agent honors `deny` (verified live) but ignores `allow`, so gated commands are
321        // VETOED rather than deferred — the only lever that adds protection.
322        assert_eq!(CursorHookFormat.gated_policy(), super::super::GatedPolicy::Deny);
323    }
324
325    #[test]
326    fn render_deny_emits_permission_deny_with_message() {
327        let r = CursorHookFormat.render_deny("safe-chains blocked this: not on the allowlist");
328        let v: Value = serde_json::from_str(&r.stdout).unwrap();
329        assert_eq!(v.get("permission").and_then(|s| s.as_str()), Some("deny"));
330        // Cursor renders `user_message` in the client and passes `agent_message` to the model.
331        assert_eq!(
332            v.get("user_message").and_then(|s| s.as_str()),
333            Some("safe-chains blocked this: not on the allowlist"),
334        );
335        assert!(v.get("agent_message").and_then(|s| s.as_str()).is_some());
336        assert!(v.get("permissionDecision").is_none());
337    }
338}