Skip to main content

lean_ctx_ext/core/
ide_permissions.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Read the active IDE's tool-permission configuration and resolve an effective
3//! action for a lean-ctx tool, so lean-ctx can *mirror* ("inherit") the user's
4//! IDE permission rules instead of forming a second, ungoverned execution path.
5//!
6//! Motivation (community request): when lean-ctx is mounted as an MCP server,
7//! its tools (e.g. `ctx_shell`) run inside the lean-ctx process and therefore
8//! bypass the host IDE's own permission engine — a user who set `bash`/`rm *`
9//! to `ask`/`deny` in their IDE would have that guard silently skipped whenever
10//! the agent reaches for `ctx_shell` instead of the native tool. This module
11//! parses the IDE permission config and lets the server gate apply an
12//! equivalent decision.
13//!
14//! v1 supports **OpenCode** (`opencode.json` / `opencode.jsonc`, global +
15//! project). The mapping is intentionally pure and side-effect-free; the server
16//! wiring (client detection, tool→key mapping, messaging, caching) lives in
17//! `server::permission_inheritance`.
18//!
19//! lean-ctx never *writes* the IDE's `permission` block — inheritance is
20//! read-only and runtime-only.
21
22use std::path::Path;
23
24use serde_json::{Map, Value};
25
26use crate::core::jsonc::parse_jsonc;
27
28/// An IDE permission decision for a single action.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum PermAction {
31    Allow,
32    Ask,
33    Deny,
34}
35
36impl PermAction {
37    fn parse(raw: &str) -> Option<Self> {
38        match raw.trim().to_ascii_lowercase().as_str() {
39            "allow" => Some(Self::Allow),
40            "ask" => Some(Self::Ask),
41            "deny" => Some(Self::Deny),
42            _ => None,
43        }
44    }
45
46    /// Restrictiveness rank used to break ties between equally specific rules
47    /// (the safer, more restrictive action wins).
48    const fn rank(self) -> u8 {
49        match self {
50            Self::Allow => 0,
51            Self::Ask => 1,
52            Self::Deny => 2,
53        }
54    }
55}
56
57/// A resolved decision together with the human-readable rule that produced it.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct PermDecision {
60    pub action: PermAction,
61    /// e.g. `bash`, `bash:rm *`, `read:*`, `*`.
62    pub rule: String,
63}
64
65/// OpenCode's documented permission keys. Used to distinguish a real tool key
66/// from a free-form bash command pattern placed at the top level.
67const OPENCODE_TOOL_KEYS: &[&str] = &[
68    "read",
69    "edit",
70    "write",
71    "patch",
72    "glob",
73    "grep",
74    "bash",
75    "task",
76    "skill",
77    "lsp",
78    "question",
79    "webfetch",
80    "websearch",
81    "external_directory",
82    "doom_loop",
83    "*",
84];
85
86/// Specificity score for the global `*` rule (lowest priority).
87const GLOBAL_SPEC: i64 = -1;
88/// Specificity score for a blanket tool rule (`bash: "allow"` or `bash: { "*": … }`).
89const BLANKET_SPEC: i64 = 0;
90
91/// Normalized IDE permission policy: the merged `permission` object from the IDE
92/// config (project entries override global ones per top-level key).
93#[derive(Debug, Clone, Default)]
94pub struct IdePermissionPolicy {
95    rules: Map<String, Value>,
96}
97
98struct Candidate {
99    spec: i64,
100    action: PermAction,
101    rule: String,
102}
103
104impl IdePermissionPolicy {
105    #[must_use]
106    pub fn is_empty(&self) -> bool {
107        self.rules.is_empty()
108    }
109
110    /// Number of top-level permission rules in the merged policy.
111    #[must_use]
112    pub fn rule_count(&self) -> usize {
113        self.rules.len()
114    }
115
116    /// Construct directly from a raw `permission` object (test/utility hook).
117    #[must_use]
118    pub fn from_rules(rules: Map<String, Value>) -> Self {
119        Self { rules }
120    }
121
122    /// Resolve the effective action for an OpenCode tool key (e.g. `bash`,
123    /// `read`) given the relevant tool input (command / path / pattern).
124    ///
125    /// Returns `None` when no rule matches — the caller treats that as the IDE
126    /// default (`allow` for the tools we mirror), so inheritance never *adds*
127    /// friction that the IDE itself would not impose.
128    ///
129    /// Resolution is order-independent (serde_json maps are not insertion-ordered
130    /// without `preserve_order`): the **most specific** rule wins (longest
131    /// pattern by non-wildcard character count; a named tool beats the global
132    /// `*`), ties broken by the **most restrictive** action.
133    #[must_use]
134    pub fn resolve(&self, tool_key: &str, input: Option<&str>) -> Option<PermDecision> {
135        let mut best: Option<Candidate> = None;
136
137        if let Some(value) = self.rules.get(tool_key) {
138            collect_from_value(value, input, tool_key, &mut best);
139        }
140
141        // For shell: also honor top-level command-like patterns. OpenCode
142        // documents these nested under `bash`, but users frequently write them
143        // at the top level (e.g. `"rm *": "ask"`); we accept both so the guard
144        // is never silently ineffective when proxied through `ctx_shell`. A
145        // command pattern is more specific than a blanket `bash: "allow"`.
146        if tool_key == "bash"
147            && let Some(cmd) = input
148        {
149            for (key, value) in &self.rules {
150                if OPENCODE_TOOL_KEYS.contains(&key.as_str()) {
151                    continue;
152                }
153                if !key.contains(' ') && !key.contains('*') {
154                    continue;
155                }
156                if let Some(action) = value.as_str().and_then(PermAction::parse)
157                    && wildcard_match(key, cmd)
158                {
159                    consider(&mut best, specificity(key), action, format!("bash:{key}"));
160                }
161            }
162        }
163
164        if let Some(action) = self
165            .rules
166            .get("*")
167            .and_then(Value::as_str)
168            .and_then(PermAction::parse)
169        {
170            consider(&mut best, GLOBAL_SPEC, action, "*".to_string());
171        }
172
173        best.map(|c| PermDecision {
174            action: c.action,
175            rule: c.rule,
176        })
177    }
178}
179
180fn collect_from_value(value: &Value, input: Option<&str>, key: &str, best: &mut Option<Candidate>) {
181    if let Some(raw) = value.as_str() {
182        if let Some(action) = PermAction::parse(raw) {
183            consider(best, BLANKET_SPEC, action, key.to_string());
184        }
185        return;
186    }
187    let Some(obj) = value.as_object() else {
188        return;
189    };
190    if let Some(inp) = input {
191        for (pat, av) in obj {
192            if pat == "*" {
193                continue;
194            }
195            if let Some(action) = av.as_str().and_then(PermAction::parse)
196                && wildcard_match(pat, inp)
197            {
198                consider(best, specificity(pat), action, format!("{key}:{pat}"));
199            }
200        }
201    }
202    if let Some(action) = obj
203        .get("*")
204        .and_then(Value::as_str)
205        .and_then(PermAction::parse)
206    {
207        consider(best, BLANKET_SPEC, action, format!("{key}:*"));
208    }
209}
210
211fn consider(best: &mut Option<Candidate>, spec: i64, action: PermAction, rule: String) {
212    let better = match best {
213        None => true,
214        Some(b) => spec > b.spec || (spec == b.spec && action.rank() > b.action.rank()),
215    };
216    if better {
217        *best = Some(Candidate { spec, action, rule });
218    }
219}
220
221/// Specificity of a glob pattern = count of non-`*` characters (more literal
222/// characters → more specific).
223fn specificity(pattern: &str) -> i64 {
224    pattern.chars().filter(|c| *c != '*').count() as i64
225}
226
227/// Minimal glob matcher supporting `*` (matches any run of characters, including
228/// empty); `**` is treated as `*`. No `?` or character classes — this mirrors
229/// the simple command/path globs OpenCode permission rules use (`git *`,
230/// `rm *`, `src/*`). Matching is case-sensitive.
231#[must_use]
232pub fn wildcard_match(pattern: &str, text: &str) -> bool {
233    let pat: Vec<char> = pattern.chars().collect();
234    let txt: Vec<char> = text.chars().collect();
235    let (mut p, mut t) = (0usize, 0usize);
236    let mut star: Option<usize> = None;
237    let mut star_t = 0usize;
238
239    while t < txt.len() {
240        if p < pat.len() && pat[p] == '*' {
241            while p + 1 < pat.len() && pat[p + 1] == '*' {
242                p += 1;
243            }
244            star = Some(p);
245            star_t = t;
246            p += 1;
247        } else if p < pat.len() && pat[p] == txt[t] {
248            p += 1;
249            t += 1;
250        } else if let Some(sp) = star {
251            p = sp + 1;
252            star_t += 1;
253            t = star_t;
254        } else {
255            return false;
256        }
257    }
258    while p < pat.len() && pat[p] == '*' {
259        p += 1;
260    }
261    p == pat.len()
262}
263
264/// Read and merge the OpenCode `permission` object: global config first, then
265/// the project config (project keys override global). Missing/invalid files are
266/// skipped silently — inheritance must never break a tool call by erroring.
267#[must_use]
268pub fn load_opencode(home: &Path, project_root: Option<&Path>) -> IdePermissionPolicy {
269    let mut rules = Map::new();
270    let opencode = home.join(".config").join("opencode");
271    merge_permission_file(&opencode.join("opencode.json"), &mut rules);
272    merge_permission_file(&opencode.join("opencode.jsonc"), &mut rules);
273    if let Some(root) = project_root {
274        merge_permission_file(&root.join("opencode.json"), &mut rules);
275        merge_permission_file(&root.join("opencode.jsonc"), &mut rules);
276    }
277    IdePermissionPolicy { rules }
278}
279
280fn merge_permission_file(path: &Path, rules: &mut Map<String, Value>) {
281    let Ok(text) = std::fs::read_to_string(path) else {
282        return;
283    };
284    let Ok(value) = parse_jsonc(&text) else {
285        return;
286    };
287    if let Some(perm) = value.get("permission").and_then(Value::as_object) {
288        for (key, val) in perm {
289            rules.insert(key.clone(), val.clone());
290        }
291    }
292}
293
294#[cfg(test)]
295pub mod tests {
296    use super::*;
297    use serde_json::json;
298
299    fn policy(v: Value) -> IdePermissionPolicy {
300        match v {
301            Value::Object(map) => IdePermissionPolicy::from_rules(map),
302            _ => IdePermissionPolicy::default(),
303        }
304    }
305
306    #[test]
307    fn wildcard_basic() {
308        assert!(wildcard_match("rm *", "rm -rf foo"));
309        assert!(wildcard_match("git *", "git status"));
310        assert!(!wildcard_match("git *", "gitk"));
311        assert!(wildcard_match("*", "anything"));
312        assert!(wildcard_match("src/*", "src/main.rs"));
313        assert!(!wildcard_match("rm *", "sudo rm -rf /"));
314        assert!(wildcard_match("**", ""));
315        assert!(wildcard_match("a*c", "abbbc"));
316        assert!(!wildcard_match("a*c", "abbb"));
317    }
318
319    #[test]
320    fn string_rule_resolves() {
321        let p = policy(json!({ "bash": "deny" }));
322        let d = p.resolve("bash", Some("ls")).unwrap();
323        assert_eq!(d.action, PermAction::Deny);
324        assert_eq!(d.rule, "bash");
325    }
326
327    #[test]
328    fn nested_bash_pattern_specific_wins() {
329        let p = policy(json!({
330            "bash": { "*": "ask", "git *": "allow", "rm *": "deny" }
331        }));
332        assert_eq!(
333            p.resolve("bash", Some("git push")).unwrap().action,
334            PermAction::Allow
335        );
336        assert_eq!(
337            p.resolve("bash", Some("rm -rf x")).unwrap().action,
338            PermAction::Deny
339        );
340        // unmatched falls back to the object's "*"
341        assert_eq!(
342            p.resolve("bash", Some("ls")).unwrap().action,
343            PermAction::Ask
344        );
345    }
346
347    #[test]
348    fn top_level_command_pattern_overrides_blanket_bash() {
349        // The exact shape from the user's screenshot: top-level "rm *": "ask"
350        // alongside a blanket bash=allow. The command pattern is more specific.
351        let p = policy(json!({ "bash": "allow", "rm *": "ask" }));
352        let d = p.resolve("bash", Some("rm -rf /tmp/x")).unwrap();
353        assert_eq!(d.action, PermAction::Ask);
354        assert_eq!(d.rule, "bash:rm *");
355        // a non-rm command falls through to the plain bash=allow
356        assert_eq!(
357            p.resolve("bash", Some("ls")).unwrap().action,
358            PermAction::Allow
359        );
360    }
361
362    #[test]
363    fn most_specific_wins_regardless_of_map_order() {
364        let p = policy(json!({ "bash": { "git *": "allow", "git push *": "ask" } }));
365        assert_eq!(
366            p.resolve("bash", Some("git push origin")).unwrap().action,
367            PermAction::Ask
368        );
369    }
370
371    #[test]
372    fn read_path_pattern() {
373        let p = policy(json!({ "read": { "*": "allow", "*.env": "deny" } }));
374        assert_eq!(
375            p.resolve("read", Some("src/main.rs")).unwrap().action,
376            PermAction::Allow
377        );
378        assert_eq!(
379            p.resolve("read", Some("prod.env")).unwrap().action,
380            PermAction::Deny
381        );
382        assert_eq!(
383            p.resolve("read", Some("config/.env")).unwrap().action,
384            PermAction::Deny
385        );
386    }
387
388    #[test]
389    fn named_tool_beats_global_wildcard() {
390        let p = policy(json!({ "*": "ask", "bash": "allow" }));
391        assert_eq!(
392            p.resolve("bash", Some("ls")).unwrap().action,
393            PermAction::Allow
394        );
395        assert_eq!(
396            p.resolve("read", Some("x")).unwrap().action,
397            PermAction::Ask
398        );
399    }
400
401    #[test]
402    fn no_rule_returns_none() {
403        let p = policy(json!({ "bash": "allow" }));
404        assert!(p.resolve("read", Some("x")).is_none());
405    }
406
407    #[test]
408    fn empty_policy_is_empty() {
409        assert!(IdePermissionPolicy::default().is_empty());
410    }
411
412    #[test]
413    fn load_opencode_merges_global_and_project() {
414        let dir = tempfile::tempdir().unwrap();
415        let home = dir.path().join("home");
416        let proj = dir.path().join("proj");
417        std::fs::create_dir_all(home.join(".config").join("opencode")).unwrap();
418        std::fs::create_dir_all(&proj).unwrap();
419        std::fs::write(
420            home.join(".config").join("opencode").join("opencode.json"),
421            r#"{ "permission": { "bash": "ask", "read": "allow" } }"#,
422        )
423        .unwrap();
424        std::fs::write(
425            proj.join("opencode.jsonc"),
426            "{ // project\n \"permission\": { \"bash\": \"deny\" } }",
427        )
428        .unwrap();
429        let p = load_opencode(&home, Some(&proj));
430        assert_eq!(
431            p.resolve("bash", Some("ls")).unwrap().action,
432            PermAction::Deny
433        );
434        assert_eq!(
435            p.resolve("read", Some("x")).unwrap().action,
436            PermAction::Allow
437        );
438    }
439
440    #[test]
441    fn load_opencode_missing_files_is_empty() {
442        let dir = tempfile::tempdir().unwrap();
443        let p = load_opencode(dir.path(), None);
444        assert!(p.is_empty());
445    }
446}