Skip to main content

a3s_code_core/permissions/
rule.rs

1use serde::{Deserialize, Serialize};
2
3/// A permission rule with pattern matching support
4///
5/// Format: `ToolName(pattern)` or `ToolName` (matches all)
6///
7/// Examples:
8/// - `Bash(cargo:*)` - matches all cargo commands
9/// - `Bash(npm run test:*)` - matches npm run test with any args
10/// - `Read(src/**/*.rs)` - matches Rust files in src/
11/// - `Grep(*)` - matches all grep invocations
12/// - `mcp__pencil` - matches all pencil MCP tools
13///
14/// Deserialization supports both plain strings and `{rule: "..."}` objects:
15/// ```yaml
16/// allow:
17///   - read                   # plain string
18///   - rule: "Bash(cargo:*)"  # struct form
19/// ```
20#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
21pub struct PermissionRule {
22    /// The original rule string
23    pub rule: String,
24    /// Parsed tool name
25    #[serde(skip)]
26    pub(crate) tool_name: Option<String>,
27    /// Parsed argument pattern (None means match all)
28    #[serde(skip)]
29    pub(crate) arg_pattern: Option<String>,
30}
31
32impl<'de> Deserialize<'de> for PermissionRule {
33    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
34    where
35        D: serde::Deserializer<'de>,
36    {
37        /// Helper enum to accept both `"read"` and `{rule: "read"}` in YAML/JSON.
38        #[derive(Deserialize)]
39        #[serde(untagged)]
40        enum RuleRepr {
41            Plain(String),
42            Struct { rule: String },
43        }
44
45        let rule_str = match RuleRepr::deserialize(deserializer)? {
46            RuleRepr::Plain(s) => s,
47            RuleRepr::Struct { rule } => rule,
48        };
49        // `new()` calls `parse_rule()` to populate tool_name and arg_pattern.
50        Ok(PermissionRule::new(&rule_str))
51    }
52}
53
54impl PermissionRule {
55    /// Create a new permission rule from a pattern string
56    pub fn new(rule: &str) -> Self {
57        let (tool_name, arg_pattern) = Self::parse_rule(rule);
58        Self {
59            rule: rule.to_string(),
60            tool_name,
61            arg_pattern,
62        }
63    }
64
65    /// Parse rule string into tool name and argument pattern
66    fn parse_rule(rule: &str) -> (Option<String>, Option<String>) {
67        // Handle format: ToolName(pattern) or ToolName
68        if let Some(paren_start) = rule.find('(') {
69            if rule.ends_with(')') {
70                let tool_name = rule[..paren_start].to_string();
71                let pattern = rule[paren_start + 1..rule.len() - 1].to_string();
72                return Self::canonicalize_search_rule(tool_name, Some(pattern));
73            }
74        }
75        // No parentheses - tool name only, matches all args
76        Self::canonicalize_search_rule(rule.to_string(), None)
77    }
78
79    /// Keep persisted policies from before the unified `search` tool working
80    /// without reserving the retired tool names in the registry. The mode is
81    /// included in the argument pattern so a legacy `grep(*)` grant does not
82    /// silently authorize glob or BM25 searches.
83    fn canonicalize_search_rule(
84        tool_name: String,
85        arg_pattern: Option<String>,
86    ) -> (Option<String>, Option<String>) {
87        let mode = match tool_name.to_ascii_lowercase().as_str() {
88            "grep" => "grep",
89            "glob" => "glob",
90            "bm25" => "bm25",
91            _ => return (Some(tool_name), arg_pattern),
92        };
93        let pattern = match arg_pattern.as_deref() {
94            None | Some("*") => format!("{mode} **"),
95            Some(pattern) => format!("{mode} {pattern}"),
96        };
97        (Some("search".to_string()), Some(pattern))
98    }
99
100    /// Check if this rule matches a tool invocation
101    pub fn matches(&self, tool_name: &str, args: &serde_json::Value) -> bool {
102        if !self.matches_tool(tool_name) {
103            return false;
104        }
105
106        // If no argument pattern, match all
107        let pattern = match &self.arg_pattern {
108            Some(p) => p,
109            None => return true,
110        };
111
112        // Match against argument pattern
113        self.matches_args(pattern, tool_name, args)
114    }
115
116    /// Whether this rule can match a tool, independent of invocation args.
117    pub(super) fn matches_tool(&self, tool_name: &str) -> bool {
118        self.tool_name
119            .as_deref()
120            .is_some_and(|rule_tool| self.matches_tool_name(rule_tool, tool_name))
121    }
122
123    /// Whether a matching tool name is denied for every possible argument.
124    pub(super) fn matches_all_args(&self) -> bool {
125        self.arg_pattern
126            .as_deref()
127            .is_none_or(|pattern| pattern == "*")
128    }
129
130    /// Check if tool names match (case-insensitive, wildcard-aware)
131    fn matches_tool_name(&self, rule_tool: &str, actual_tool: &str) -> bool {
132        // If the rule contains wildcards, use glob matching on the tool name directly.
133        // e.g. "mcp__longvt__*" must use glob, not starts_with, because starts_with
134        // treats '*' as a literal character and will never match.
135        if rule_tool.contains('*') || rule_tool.contains('?') {
136            return self.glob_match(rule_tool, actual_tool);
137        }
138
139        // Handle MCP tools: mcp__server matches mcp__server__tool
140        if rule_tool.starts_with("mcp__") && actual_tool.starts_with("mcp__") {
141            // mcp__pencil matches mcp__pencil__batch_design
142            if actual_tool.starts_with(rule_tool) {
143                return true;
144            }
145        }
146        rule_tool.eq_ignore_ascii_case(actual_tool)
147    }
148
149    /// Match argument pattern against tool arguments
150    fn matches_args(&self, pattern: &str, tool_name: &str, args: &serde_json::Value) -> bool {
151        // Handle wildcard pattern "*" - matches everything
152        if pattern == "*" {
153            return true;
154        }
155
156        // Build argument string based on tool type
157        let arg_string = self.build_arg_string(tool_name, args);
158
159        // Perform glob-style matching
160        self.glob_match(pattern, &arg_string)
161    }
162
163    /// Build a string representation of arguments for matching
164    fn build_arg_string(&self, tool_name: &str, args: &serde_json::Value) -> String {
165        match tool_name.to_lowercase().as_str() {
166            "bash" => {
167                // For Bash, use the command field
168                args.get("command")
169                    .and_then(|v| v.as_str())
170                    .unwrap_or("")
171                    .to_string()
172            }
173            "read" | "write" | "edit" | "download" => {
174                // For file operations, use the file_path field
175                args.get("file_path")
176                    .and_then(|v| v.as_str())
177                    .unwrap_or("")
178                    .to_string()
179            }
180            "search" => {
181                // For repository search, combine the mode, query, and path.
182                let mode = args.get("mode").and_then(|v| v.as_str()).unwrap_or("");
183                let query = args.get("query").and_then(|v| v.as_str()).unwrap_or("");
184                let path = args.get("path").and_then(|v| v.as_str()).unwrap_or("");
185                format!("{} {} {}", mode, query, path)
186            }
187            "ls" => {
188                // For ls, use the path field
189                args.get("path")
190                    .and_then(|v| v.as_str())
191                    .unwrap_or("")
192                    .to_string()
193            }
194            _ => {
195                // For other tools, serialize the entire args
196                serde_json::to_string(args).unwrap_or_default()
197            }
198        }
199    }
200
201    /// Perform glob-style pattern matching
202    ///
203    /// Supports:
204    /// - `*` matches any sequence of characters (except /)
205    /// - `**` matches any sequence including /
206    /// - `:*` at the end matches any suffix (including empty)
207    fn glob_match(&self, pattern: &str, text: &str) -> bool {
208        // Handle special `:*` suffix (matches any args after the prefix)
209        if let Some(prefix) = pattern.strip_suffix(":*") {
210            return text.starts_with(prefix);
211        }
212
213        // Normalize Windows backslashes to forward slashes for consistent matching
214        let text = text.replace('\\', "/");
215
216        // Convert glob pattern to regex pattern
217        let regex_pattern = Self::glob_to_regex(pattern);
218        if let Ok(re) = regex::Regex::new(&regex_pattern) {
219            re.is_match(&text)
220        } else {
221            // Fallback to simple prefix match if regex fails
222            text.starts_with(pattern)
223        }
224    }
225
226    /// Convert glob pattern to regex pattern
227    fn glob_to_regex(pattern: &str) -> String {
228        let mut regex = String::from("^");
229        let chars: Vec<char> = pattern.chars().collect();
230        let mut i = 0;
231
232        while i < chars.len() {
233            let c = chars[i];
234            match c {
235                '*' => {
236                    // Check for ** (matches anything including /)
237                    if i + 1 < chars.len() && chars[i + 1] == '*' {
238                        // ** matches any path including /
239                        // Skip optional following /
240                        if i + 2 < chars.len() && chars[i + 2] == '/' {
241                            regex.push_str(".*");
242                            i += 3;
243                        } else {
244                            regex.push_str(".*");
245                            i += 2;
246                        }
247                    } else {
248                        // * matches anything except path separators
249                        regex.push_str("[^/\\\\]*");
250                        i += 1;
251                    }
252                }
253                '?' => {
254                    // ? matches any single character except path separators
255                    regex.push_str("[^/\\\\]");
256                    i += 1;
257                }
258                '.' | '+' | '^' | '$' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | '\\' => {
259                    // Escape regex special characters
260                    regex.push('\\');
261                    regex.push(c);
262                    i += 1;
263                }
264                _ => {
265                    regex.push(c);
266                    i += 1;
267                }
268            }
269        }
270
271        regex.push('$');
272        regex
273    }
274}