Skip to main content

vtcode_core/
permissions.rs

1use glob::Pattern;
2use ignore::gitignore::{Gitignore, GitignoreBuilder};
3use serde_json::{Value, json};
4use std::path::{Path, PathBuf};
5use url::Url;
6
7use crate::config::PermissionsConfig;
8use crate::config::constants::tools;
9use crate::tools::command_args;
10use crate::tools::mcp::{MCP_QUALIFIED_TOOL_PREFIX, parse_canonical_mcp_tool_name};
11use crate::tools::tool_intent;
12use vtcode_config::core::permissions::{AgentPermissionsConfig, PermissionDefault, normalize_permission_rule};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15#[must_use = "permission decisions must be enforced"]
16pub enum PermissionRuleDecision {
17    Allow,
18    Auto,
19    Ask,
20    Deny,
21    NoMatch,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25#[must_use = "permission decisions must be enforced"]
26pub enum ResolvedPermissionDecision {
27    Allow,
28    Auto,
29    Ask,
30    Deny,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
34pub struct PermissionRuleMatches {
35    pub deny: bool,
36    pub ask: bool,
37    pub auto: bool,
38    pub allow: bool,
39}
40
41impl PermissionRuleMatches {
42    /// Converts these matches into a single [`PermissionRuleDecision`] using deny > ask > auto > allow precedence.
43    pub const fn decision(self) -> PermissionRuleDecision {
44        if self.deny {
45            PermissionRuleDecision::Deny
46        } else if self.ask {
47            PermissionRuleDecision::Ask
48        } else if self.auto {
49            PermissionRuleDecision::Auto
50        } else if self.allow {
51            PermissionRuleDecision::Allow
52        } else {
53            PermissionRuleDecision::NoMatch
54        }
55    }
56}
57
58/// Categorizes a permission request by the type of operation being performed.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum PermissionRequestKind {
61    /// A shell command execution request.
62    Bash { command: String },
63    /// A file read request targeting the given paths.
64    Read { paths: Vec<PathBuf> },
65    /// A file edit request targeting the given paths.
66    Edit { paths: Vec<PathBuf> },
67    /// A file write/create/delete request targeting the given paths.
68    Write { paths: Vec<PathBuf> },
69    /// A web fetch request targeting the given domains.
70    WebFetch { domains: Vec<String> },
71    /// An MCP tool invocation for the given server and tool.
72    Mcp { server: String, tool: String },
73    /// A tool call that does not fit the categories above.
74    Other,
75}
76
77/// A fully described permission request carrying the tool name, operation kind,
78/// and any protected-path metadata needed for prompting.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct PermissionRequest {
81    /// Exact (normalized) tool name that originated this request.
82    pub exact_tool_name: String,
83    /// Categorized operation kind for rule matching.
84    pub kind: PermissionRequestKind,
85    /// Whether this request mutates a file via a builtin file tool.
86    pub builtin_file_mutation: bool,
87    /// Paths within protected directories (`.git`, `.vtcode`, etc.) that require extra confirmation.
88    pub protected_write_paths: Vec<PathBuf>,
89}
90
91impl PermissionRequest {
92    /// Returns `true` if this request targets one or more protected write paths.
93    pub fn requires_protected_write_prompt(&self) -> bool {
94        !self.protected_write_paths.is_empty()
95    }
96}
97
98/// Constructs a [`PermissionRequest`] from a normalized tool name and its arguments.
99pub fn build_permission_request(
100    workspace_root: &Path,
101    current_dir: &Path,
102    normalized_tool_name: &str,
103    tool_args: Option<&Value>,
104) -> PermissionRequest {
105    let kind = build_request_kind(workspace_root, current_dir, normalized_tool_name, tool_args);
106    let protected_write_paths = protected_write_paths(workspace_root, &kind);
107    let builtin_file_mutation =
108        matches!(kind, PermissionRequestKind::Edit { .. } | PermissionRequestKind::Write { .. });
109
110    PermissionRequest {
111        exact_tool_name: normalized_tool_name.to_string(),
112        kind,
113        builtin_file_mutation,
114        protected_write_paths,
115    }
116}
117
118/// Build representative permission requests for advertised tool availability.
119///
120/// Runtime dispatch still evaluates the concrete call arguments. Advertisement cannot know future
121/// arguments, so multi-action tools include each category they can expose and callers should treat
122/// any denied representative request as a reason not to grant provider-native availability.
123pub fn build_advertised_permission_requests(
124    workspace_root: &Path,
125    current_dir: &Path,
126    normalized_tool_name: &str,
127) -> Vec<PermissionRequest> {
128    let representative_args = advertised_permission_args(normalized_tool_name);
129    if representative_args.is_empty() {
130        return vec![build_permission_request(
131            workspace_root,
132            current_dir,
133            normalized_tool_name,
134            None,
135        )];
136    }
137
138    representative_args
139        .iter()
140        .map(|args| build_permission_request(workspace_root, current_dir, normalized_tool_name, Some(args)))
141        .collect()
142}
143
144/// Evaluates a permission request against the global permission configuration and
145/// returns which rule tiers matched.
146pub fn evaluate_permissions(
147    config: &PermissionsConfig,
148    workspace_root: &Path,
149    current_dir: &Path,
150    request: &PermissionRequest,
151) -> PermissionRuleMatches {
152    let evaluator = PermissionRuleSet::from_global_config(config, workspace_root, current_dir);
153    evaluator.evaluate_matches(request)
154}
155
156/// Evaluates a permission request against an agent's permission configuration,
157/// returning the resolved decision using the agent's default when no rule matches.
158pub fn evaluate_agent_permissions(
159    agent_permissions: &AgentPermissionsConfig,
160    workspace_root: &Path,
161    current_dir: &Path,
162    request: &PermissionRequest,
163) -> ResolvedPermissionDecision {
164    let evaluator = PermissionRuleSet::from_agent_config(agent_permissions, workspace_root, current_dir);
165    evaluator.resolve(request, agent_permissions.default)
166}
167
168/// Evaluates a permission request by combining global and agent-level rules.
169/// Global deny is a hard ceiling; global ask forces a prompt unless the agent denies.
170pub fn evaluate_effective_permissions(
171    global_config: &PermissionsConfig,
172    agent_permissions: &AgentPermissionsConfig,
173    workspace_root: &Path,
174    current_dir: &Path,
175    request: &PermissionRequest,
176) -> ResolvedPermissionDecision {
177    let global = PermissionRuleSet::from_global_config(global_config, workspace_root, current_dir);
178    let global_matches = global.evaluate_matches(request);
179    if global_matches.deny {
180        return ResolvedPermissionDecision::Deny;
181    }
182
183    let agent_decision = evaluate_agent_permissions(agent_permissions, workspace_root, current_dir, request);
184    if global_matches.ask && agent_decision != ResolvedPermissionDecision::Deny {
185        return ResolvedPermissionDecision::Ask;
186    }
187
188    agent_decision
189}
190
191struct PermissionRuleSet {
192    deny: Vec<CompiledPermissionRule>,
193    ask: Vec<CompiledPermissionRule>,
194    auto: Vec<CompiledPermissionRule>,
195    allow: Vec<CompiledPermissionRule>,
196}
197
198impl PermissionRuleSet {
199    fn from_global_config(config: &PermissionsConfig, workspace_root: &Path, current_dir: &Path) -> Self {
200        Self {
201            deny: compile_rules(&config.deny, workspace_root, current_dir),
202            ask: compile_rules(&config.ask, workspace_root, current_dir),
203            auto: Vec::new(),
204            allow: compile_rules(&config.allow, workspace_root, current_dir),
205        }
206    }
207
208    fn from_agent_config(config: &AgentPermissionsConfig, workspace_root: &Path, current_dir: &Path) -> Self {
209        Self {
210            deny: compile_rules(&config.deny, workspace_root, current_dir),
211            ask: compile_rules(&config.ask, workspace_root, current_dir),
212            auto: compile_rules(&config.auto, workspace_root, current_dir),
213            allow: compile_rules(&config.allow, workspace_root, current_dir),
214        }
215    }
216
217    fn evaluate_matches(&self, request: &PermissionRequest) -> PermissionRuleMatches {
218        PermissionRuleMatches {
219            deny: self.deny.iter().any(|rule| rule.matches(request)),
220            ask: self.ask.iter().any(|rule| rule.matches(request)),
221            auto: self.auto.iter().any(|rule| rule.matches(request)),
222            allow: self.allow.iter().any(|rule| rule.matches(request)),
223        }
224    }
225
226    fn resolve(&self, request: &PermissionRequest, default: PermissionDefault) -> ResolvedPermissionDecision {
227        let matches = self.evaluate_matches(request);
228        if matches.deny {
229            ResolvedPermissionDecision::Deny
230        } else if matches.ask {
231            ResolvedPermissionDecision::Ask
232        } else if matches.auto {
233            ResolvedPermissionDecision::Auto
234        } else if matches.allow {
235            ResolvedPermissionDecision::Allow
236        } else {
237            default.into()
238        }
239    }
240}
241
242impl From<PermissionDefault> for ResolvedPermissionDecision {
243    fn from(default: PermissionDefault) -> Self {
244        match default {
245            PermissionDefault::Ask => Self::Ask,
246            PermissionDefault::Allow => Self::Allow,
247            PermissionDefault::Auto => Self::Auto,
248            PermissionDefault::Deny => Self::Deny,
249        }
250    }
251}
252
253fn compile_rules(rules: &[String], workspace_root: &Path, current_dir: &Path) -> Vec<CompiledPermissionRule> {
254    rules
255        .iter()
256        .filter_map(|rule| CompiledPermissionRule::compile(rule, workspace_root, current_dir))
257        .collect()
258}
259
260#[derive(Debug)]
261enum CompiledPermissionRule {
262    Bash(Option<Pattern>),
263    Read(Option<PathRuleMatcher>),
264    Edit(Option<PathRuleMatcher>),
265    Write(Option<PathRuleMatcher>),
266    WebFetchAll,
267    WebFetchDomain(String),
268    McpServer(String),
269    McpWildcard(String),
270    McpTool { server: String, tool: String },
271    ExactTool(String),
272}
273
274impl CompiledPermissionRule {
275    fn compile(raw: &str, workspace_root: &Path, current_dir: &Path) -> Option<Self> {
276        let rule = normalize_permission_rule(raw);
277        let rule = rule.trim();
278        if rule.is_empty() {
279            return None;
280        }
281
282        if rule.eq_ignore_ascii_case("bash") || rule.eq_ignore_ascii_case("bash(*)") {
283            return Some(Self::Bash(None));
284        }
285        if let Some(specifier) = parse_tool_specifier(rule, "bash") {
286            return compile_bash_rule(specifier).map(Self::Bash);
287        }
288
289        if rule.eq_ignore_ascii_case("read") || rule.eq_ignore_ascii_case("read(*)") {
290            return Some(Self::Read(None));
291        }
292        if let Some(specifier) = parse_tool_specifier(rule, "read") {
293            return PathRuleMatcher::compile(specifier, workspace_root, current_dir)
294                .map(Some)
295                .map(Self::Read);
296        }
297
298        if rule.eq_ignore_ascii_case("edit") || rule.eq_ignore_ascii_case("edit(*)") {
299            return Some(Self::Edit(None));
300        }
301        if let Some(specifier) = parse_tool_specifier(rule, "edit") {
302            return PathRuleMatcher::compile(specifier, workspace_root, current_dir)
303                .map(Some)
304                .map(Self::Edit);
305        }
306
307        if rule.eq_ignore_ascii_case("write") || rule.eq_ignore_ascii_case("write(*)") {
308            return Some(Self::Write(None));
309        }
310        if let Some(specifier) = parse_tool_specifier(rule, "write") {
311            return PathRuleMatcher::compile(specifier, workspace_root, current_dir)
312                .map(Some)
313                .map(Self::Write);
314        }
315
316        if rule.eq_ignore_ascii_case("webfetch") || rule.eq_ignore_ascii_case("webfetch(*)") {
317            return Some(Self::WebFetchAll);
318        }
319        if let Some(specifier) = parse_tool_specifier(rule, "webfetch") {
320            let domain = specifier.strip_prefix("domain:")?.trim().to_ascii_lowercase();
321            if domain.is_empty() {
322                return None;
323            }
324            return Some(Self::WebFetchDomain(domain));
325        }
326
327        if let Some(server) = rule.strip_prefix(MCP_QUALIFIED_TOOL_PREFIX) {
328            if let Some((server, tool)) = server.split_once("__") {
329                if tool == "*" {
330                    return Some(Self::McpWildcard(server.to_string()));
331                }
332                if !server.is_empty() && !tool.is_empty() {
333                    return Some(Self::McpTool { server: server.to_string(), tool: tool.to_string() });
334                }
335                return None;
336            }
337            if !server.is_empty() {
338                return Some(Self::McpServer(server.to_string()));
339            }
340            return None;
341        }
342
343        if rule.contains('(') || rule.contains(')') {
344            return None;
345        }
346
347        Some(Self::ExactTool(rule.to_string()))
348    }
349
350    fn matches(&self, request: &PermissionRequest) -> bool {
351        match self {
352            Self::Bash(pattern) => match &request.kind {
353                PermissionRequestKind::Bash { command } => {
354                    pattern.as_ref().is_none_or(|pattern| pattern.matches(command))
355                }
356                _ => false,
357            },
358            Self::Read(matcher) => match &request.kind {
359                PermissionRequestKind::Read { paths } => matcher
360                    .as_ref()
361                    .is_none_or(|matcher| paths.iter().any(|path| matcher.matches(path))),
362                _ => false,
363            },
364            Self::Edit(matcher) => match &request.kind {
365                PermissionRequestKind::Edit { paths } => matcher
366                    .as_ref()
367                    .is_none_or(|matcher| paths.iter().any(|path| matcher.matches(path))),
368                _ => false,
369            },
370            Self::Write(matcher) => match &request.kind {
371                PermissionRequestKind::Write { paths } => matcher
372                    .as_ref()
373                    .is_none_or(|matcher| paths.iter().any(|path| matcher.matches(path))),
374                _ => false,
375            },
376            Self::WebFetchAll => matches!(request.kind, PermissionRequestKind::WebFetch { .. }),
377            Self::WebFetchDomain(domain) => match &request.kind {
378                PermissionRequestKind::WebFetch { domains } => {
379                    domains.iter().any(|candidate| domain_matches_allowed(candidate, domain))
380                }
381                _ => false,
382            },
383            Self::McpServer(server) | Self::McpWildcard(server) => match &request.kind {
384                PermissionRequestKind::Mcp { server: candidate, .. } => candidate == server,
385                _ => false,
386            },
387            Self::McpTool { server, tool } => match &request.kind {
388                PermissionRequestKind::Mcp { server: candidate_server, tool: candidate_tool } => {
389                    candidate_server == server && candidate_tool == tool
390                }
391                _ => false,
392            },
393            Self::ExactTool(tool_name) => request.exact_tool_name == *tool_name,
394        }
395    }
396}
397
398fn parse_tool_specifier<'a>(rule: &'a str, tool_name: &str) -> Option<&'a str> {
399    let open = rule.find('(')?;
400    let close = rule.rfind(')')?;
401    if close <= open || close + 1 != rule.len() {
402        return None;
403    }
404    let prefix = &rule[..open];
405    prefix.eq_ignore_ascii_case(tool_name).then_some(rule[open + 1..close].trim())
406}
407
408fn compile_bash_rule(specifier: &str) -> Option<Option<Pattern>> {
409    if specifier.is_empty() || specifier == "*" {
410        return Some(None);
411    }
412    Pattern::new(specifier).ok().map(Some)
413}
414
415#[derive(Debug)]
416struct PathRuleMatcher {
417    matcher: Gitignore,
418}
419
420impl PathRuleMatcher {
421    fn compile(raw: &str, workspace_root: &Path, current_dir: &Path) -> Option<Self> {
422        let home_dir = dirs::home_dir();
423        let (root, pattern) = if let Some(path) = raw.strip_prefix("//") {
424            (PathBuf::from("/"), format!("/{path}"))
425        } else if let Some(path) = raw.strip_prefix("~/") {
426            (home_dir?, format!("/{path}"))
427        } else if raw.starts_with('/') {
428            (workspace_root.to_path_buf(), raw.to_string())
429        } else if let Some(path) = raw.strip_prefix("./") {
430            (current_dir.to_path_buf(), path.to_string())
431        } else {
432            (current_dir.to_path_buf(), raw.to_string())
433        };
434
435        let mut builder = GitignoreBuilder::new(root);
436        builder.add_line(None, &pattern).ok()?;
437        let matcher = builder.build().ok()?;
438        Some(Self { matcher })
439    }
440
441    fn matches(&self, candidate: &Path) -> bool {
442        self.matcher.matched_path_or_any_parents(candidate, false).is_ignore()
443    }
444}
445
446fn build_request_kind(
447    workspace_root: &Path,
448    current_dir: &Path,
449    normalized_tool_name: &str,
450    tool_args: Option<&Value>,
451) -> PermissionRequestKind {
452    if let Some((server, tool)) = parse_mcp_request(normalized_tool_name) {
453        return PermissionRequestKind::Mcp { server, tool };
454    }
455
456    if normalized_tool_name == tools::CODE_SEARCH {
457        let paths = tool_args.map_or_else(Vec::new, |args| {
458            extract_candidate_paths(workspace_root, current_dir, normalized_tool_name, args)
459        });
460        return PermissionRequestKind::Read { paths };
461    }
462
463    let Some(args) = tool_args else {
464        return PermissionRequestKind::Other;
465    };
466
467    if normalized_tool_name == tools::EXEC_COMMAND {
468        let command = command_args::command_text(args).ok().flatten().unwrap_or_default();
469        return PermissionRequestKind::Bash { command };
470    }
471
472    if tool_intent::is_command_run_tool_call(normalized_tool_name, args)
473        && let Ok(Some(command)) = command_args::command_text(args)
474    {
475        return PermissionRequestKind::Bash { command };
476    }
477
478    if is_web_fetch_request(normalized_tool_name, args) {
479        let domains = extract_web_domains(args);
480        return PermissionRequestKind::WebFetch { domains };
481    }
482
483    if let Some(kind) = file_request_kind(workspace_root, current_dir, normalized_tool_name, args) {
484        return kind;
485    }
486
487    PermissionRequestKind::Other
488}
489
490fn advertised_permission_args(normalized_tool_name: &str) -> Vec<Value> {
491    match normalized_tool_name {
492        tools::UNIFIED_EXEC | tools::EXEC_PTY_CMD | "exec" => {
493            vec![json!({ "action": "run", "command": "true" })]
494        }
495        tools::EXEC_COMMAND => vec![json!({ "cmd": "rg --files" })],
496        tools::RUN_PTY_CMD | tools::CREATE_PTY_SESSION | tools::SHELL | "bash" => {
497            vec![json!({ "command": "true" })]
498        }
499        tools::READ_FILE | tools::GREP_FILE | tools::LIST_FILES => {
500            vec![json!({ "path": "." })]
501        }
502        tools::CODE_SEARCH => vec![json!({ "query": "probe", "path": "." })],
503        tools::WRITE_FILE | tools::CREATE_FILE | tools::DELETE_FILE => {
504            vec![json!({ "path": "advertised-permission-probe.txt" })]
505        }
506        tools::MOVE_FILE | tools::COPY_FILE => vec![json!({
507            "path": "advertised-permission-probe.txt",
508            "destination": "advertised-permission-probe-copy.txt"
509        })],
510        tools::EDIT_FILE | tools::SEARCH_REPLACE => {
511            vec![json!({ "path": "advertised-permission-probe.txt" })]
512        }
513        tools::APPLY_PATCH => vec![json!({
514            "patch": "*** Begin Patch\n*** Update File: advertised-permission-probe.txt\n@@\n-old\n+new\n*** End Patch\n"
515        })],
516        tools::FILE_OP => vec![json!({ "path": "advertised-permission-probe.txt" })],
517        tools::UNIFIED_FILE => vec![
518            json!({ "action": "read", "path": "." }),
519            json!({ "action": "edit", "path": "advertised-permission-probe.txt" }),
520            json!({ "action": "write", "path": "advertised-permission-probe.txt" }),
521        ],
522        tools::WEB_FETCH | tools::FETCH_URL => vec![json!({ "url": "https://example.com/" })],
523        _ => Vec::new(),
524    }
525}
526
527fn parse_mcp_request(normalized_tool_name: &str) -> Option<(String, String)> {
528    if let Some((server, tool)) = parse_canonical_mcp_tool_name(normalized_tool_name) {
529        return Some((server.to_string(), tool.to_string()));
530    }
531
532    let stripped = normalized_tool_name.strip_prefix(MCP_QUALIFIED_TOOL_PREFIX)?;
533    let (server, tool) = stripped.split_once("__")?;
534    if server.is_empty() || tool.is_empty() || tool == "*" {
535        return None;
536    }
537    Some((server.to_string(), tool.to_string()))
538}
539
540fn is_web_fetch_request(normalized_tool_name: &str, _args: &Value) -> bool {
541    normalized_tool_name == tools::WEB_FETCH || normalized_tool_name == tools::FETCH_URL
542}
543
544fn file_request_kind(
545    workspace_root: &Path,
546    current_dir: &Path,
547    normalized_tool_name: &str,
548    args: &Value,
549) -> Option<PermissionRequestKind> {
550    let paths = extract_candidate_paths(workspace_root, current_dir, normalized_tool_name, args);
551
552    match normalized_tool_name {
553        tools::READ_FILE | tools::GREP_FILE | tools::LIST_FILES | tools::CODE_SEARCH => {
554            Some(PermissionRequestKind::Read { paths })
555        }
556        tools::WRITE_FILE | tools::CREATE_FILE | tools::DELETE_FILE | tools::MOVE_FILE | tools::COPY_FILE => {
557            Some(PermissionRequestKind::Write { paths })
558        }
559        tools::EDIT_FILE | tools::APPLY_PATCH | tools::SEARCH_REPLACE | tools::FILE_OP => {
560            Some(PermissionRequestKind::Edit { paths })
561        }
562        tools::UNIFIED_FILE => match tool_intent::file_operation_action(args) {
563            Some("read") => Some(PermissionRequestKind::Read { paths }),
564            Some("edit") | Some("patch") => Some(PermissionRequestKind::Edit { paths }),
565            Some(_) => Some(PermissionRequestKind::Write { paths }),
566            None => None,
567        },
568        _ => None,
569    }
570}
571
572fn extract_candidate_paths(
573    workspace_root: &Path,
574    current_dir: &Path,
575    normalized_tool_name: &str,
576    args: &Value,
577) -> Vec<PathBuf> {
578    let mut paths = Vec::new();
579
580    if let Some(obj) = args.as_object() {
581        for key in ["path", "file_path", "filepath", "target_path", "destination"] {
582            if let Some(path) = obj.get(key).and_then(Value::as_str) {
583                push_resolved_path(&mut paths, workspace_root, current_dir, path);
584            }
585        }
586    }
587
588    if normalized_tool_name == tools::APPLY_PATCH {
589        for patch_path in extract_patch_paths(args) {
590            push_resolved_path(&mut paths, workspace_root, current_dir, &patch_path);
591        }
592    }
593
594    paths.sort();
595    paths.dedup();
596    paths
597}
598
599fn extract_patch_paths(args: &Value) -> Vec<String> {
600    let patch = args
601        .get("patch")
602        .and_then(Value::as_str)
603        .or_else(|| args.get("input").and_then(Value::as_str))
604        .or_else(|| args.as_str());
605    let Some(patch) = patch else {
606        return Vec::new();
607    };
608
609    patch
610        .lines()
611        .filter_map(|line| {
612            for prefix in [
613                "*** Update File: ",
614                "*** Add File: ",
615                "*** Delete File: ",
616                "*** Move to: ",
617            ] {
618                if let Some(path) = line.strip_prefix(prefix) {
619                    let trimmed = path.trim();
620                    if !trimmed.is_empty() {
621                        return Some(trimmed.to_string());
622                    }
623                }
624            }
625            None
626        })
627        .collect()
628}
629
630fn push_resolved_path(paths: &mut Vec<PathBuf>, workspace_root: &Path, current_dir: &Path, raw: &str) {
631    let trimmed = raw.trim();
632    if trimmed.is_empty() {
633        return;
634    }
635
636    let resolved = if Path::new(trimmed).is_absolute() {
637        PathBuf::from(trimmed)
638    } else {
639        current_dir
640            .strip_prefix(workspace_root)
641            .ok()
642            .filter(|relative| !relative.as_os_str().is_empty())
643            .map(|relative| workspace_root.join(relative).join(trimmed))
644            .unwrap_or_else(|| workspace_root.join(trimmed))
645    };
646    paths.push(crate::utils::path::normalize_path(&resolved));
647}
648
649fn extract_web_domains(args: &Value) -> Vec<String> {
650    args.get("url")
651        .and_then(Value::as_str)
652        .and_then(extract_url_domain)
653        .into_iter()
654        .collect::<Vec<_>>()
655}
656
657fn extract_url_domain(url: &str) -> Option<String> {
658    let parsed = Url::parse(url).ok()?;
659    parsed.host_str().map(|host| host.trim_end_matches('.').to_ascii_lowercase())
660}
661
662fn protected_write_paths(workspace_root: &Path, kind: &PermissionRequestKind) -> Vec<PathBuf> {
663    let paths = match kind {
664        PermissionRequestKind::Edit { paths } | PermissionRequestKind::Write { paths } => paths,
665        _ => return Vec::new(),
666    };
667
668    paths
669        .iter()
670        .filter(|path| is_protected_write_path(workspace_root, path))
671        .cloned()
672        .collect()
673}
674
675fn is_protected_write_path(workspace_root: &Path, path: &Path) -> bool {
676    let relative = path.strip_prefix(workspace_root).ok();
677    let Some(relative) = relative else {
678        return false;
679    };
680
681    let as_string = relative.to_string_lossy().replace('\\', "/");
682    if matches!(as_string.as_str(), ".vtcode/commands" | ".vtcode/agents" | ".vtcode/skills")
683        || as_string.starts_with(".vtcode/commands/")
684        || as_string.starts_with(".vtcode/agents/")
685        || as_string.starts_with(".vtcode/skills/")
686    {
687        return false;
688    }
689
690    matches!(as_string.split('/').next(), Some(".git" | ".vtcode" | ".vscode" | ".idea"))
691}
692
693fn domain_matches_allowed(domain: &str, allowed: &str) -> bool {
694    let normalized_domain = domain.trim_end_matches('.').to_ascii_lowercase();
695    let normalized_allowed = allowed.trim_start_matches('.').trim_end_matches('.').to_ascii_lowercase();
696
697    normalized_domain == normalized_allowed || normalized_domain.ends_with(&format!(".{normalized_allowed}"))
698}
699
700#[cfg(test)]
701mod tests {
702    use super::{
703        PermissionRequest, PermissionRequestKind, PermissionRuleDecision, ResolvedPermissionDecision,
704        build_advertised_permission_requests, build_permission_request, evaluate_agent_permissions,
705        evaluate_effective_permissions, evaluate_permissions,
706    };
707    use crate::config::{PermissionsConfig, constants::tools};
708    use serde_json::json;
709    use tempfile::TempDir;
710    use vtcode_config::core::permissions::{AgentPermissionsConfig, PermissionDefault};
711
712    fn workspace_roots() -> (TempDir, std::path::PathBuf, std::path::PathBuf) {
713        let temp = TempDir::new().expect("temp dir");
714        let workspace = temp.path().join("workspace");
715        let cwd = workspace.join("nested");
716        std::fs::create_dir_all(&cwd).expect("create dirs");
717        (temp, workspace, cwd)
718    }
719
720    fn agent_permissions(default: PermissionDefault) -> AgentPermissionsConfig {
721        AgentPermissionsConfig::new(default)
722    }
723
724    fn exact_tool_request(tool_name: &str) -> PermissionRequest {
725        PermissionRequest {
726            exact_tool_name: tool_name.to_string(),
727            kind: PermissionRequestKind::Other,
728            builtin_file_mutation: false,
729            protected_write_paths: Vec::new(),
730        }
731    }
732
733    #[test]
734    fn deny_precedes_ask_and_allow() {
735        let (_temp, workspace, cwd) = workspace_roots();
736        let config = PermissionsConfig {
737            allow: vec!["Read".to_string()],
738            ask: vec!["Read(/docs/**)".to_string()],
739            deny: vec!["Read(/docs/secret.txt)".to_string()],
740            ..PermissionsConfig::default()
741        };
742        let request = PermissionRequest {
743            exact_tool_name: "read_file".to_string(),
744            kind: PermissionRequestKind::Read { paths: vec![workspace.join("docs/secret.txt")] },
745            builtin_file_mutation: false,
746            protected_write_paths: Vec::new(),
747        };
748
749        assert_eq!(evaluate_permissions(&config, &workspace, &cwd, &request).decision(), PermissionRuleDecision::Deny);
750    }
751
752    #[test]
753    fn bash_glob_matches_command_text() {
754        let (_temp, workspace, cwd) = workspace_roots();
755        let config = PermissionsConfig {
756            allow: vec!["Bash(cargo test *)".to_string()],
757            ..PermissionsConfig::default()
758        };
759        let request = PermissionRequest {
760            exact_tool_name: "command_session".to_string(),
761            kind: PermissionRequestKind::Bash { command: "cargo test -p vtcode".to_string() },
762            builtin_file_mutation: false,
763            protected_write_paths: Vec::new(),
764        };
765
766        assert_eq!(evaluate_permissions(&config, &workspace, &cwd, &request).decision(), PermissionRuleDecision::Allow);
767    }
768
769    #[test]
770    fn read_path_rules_use_workspace_relative_matching() {
771        let (_temp, workspace, cwd) = workspace_roots();
772        let config = PermissionsConfig {
773            ask: vec!["Read(/src/**/*.rs)".to_string()],
774            ..PermissionsConfig::default()
775        };
776        let request = PermissionRequest {
777            exact_tool_name: "read_file".to_string(),
778            kind: PermissionRequestKind::Read { paths: vec![workspace.join("src/lib.rs")] },
779            builtin_file_mutation: false,
780            protected_write_paths: Vec::new(),
781        };
782
783        assert_eq!(evaluate_permissions(&config, &workspace, &cwd, &request).decision(), PermissionRuleDecision::Ask);
784    }
785
786    #[test]
787    fn mcp_rules_match_canonical_requests() {
788        let (_temp, workspace, cwd) = workspace_roots();
789        let config = PermissionsConfig {
790            allow: vec!["mcp__context7__*".to_string()],
791            ..PermissionsConfig::default()
792        };
793        let request = PermissionRequest {
794            exact_tool_name: "mcp::context7::search-docs".to_string(),
795            kind: PermissionRequestKind::Mcp {
796                server: "context7".to_string(),
797                tool: "search-docs".to_string(),
798            },
799            builtin_file_mutation: false,
800            protected_write_paths: Vec::new(),
801        };
802
803        assert_eq!(evaluate_permissions(&config, &workspace, &cwd, &request).decision(), PermissionRuleDecision::Allow);
804    }
805
806    #[test]
807    fn protected_directory_exceptions_are_not_flagged() {
808        let (_temp, workspace, cwd) = workspace_roots();
809        let request = build_permission_request(
810            &workspace,
811            &cwd,
812            tools::UNIFIED_FILE,
813            Some(&json!({
814                "action": "write",
815                "path": "../.vtcode/skills/example.md"
816            })),
817        );
818        assert!(!request.requires_protected_write_prompt());
819
820        let request = build_permission_request(
821            &workspace,
822            &cwd,
823            tools::UNIFIED_FILE,
824            Some(&json!({
825                "action": "write",
826                "path": "../.vtcode/settings.toml"
827            })),
828        );
829        assert!(request.requires_protected_write_prompt());
830    }
831
832    #[test]
833    fn apply_patch_paths_are_extracted_for_edit_rules() {
834        let (_temp, workspace, cwd) = workspace_roots();
835        let config = PermissionsConfig {
836            ask: vec!["Edit(/src/**)".to_string()],
837            ..PermissionsConfig::default()
838        };
839        let request = build_permission_request(
840            &workspace,
841            &cwd,
842            "apply_patch",
843            Some(&json!({
844                "patch": "*** Begin Patch\n*** Update File: ../src/main.rs\n@@\n-test\n+test\n*** End Patch\n"
845            })),
846        );
847
848        assert_eq!(evaluate_permissions(&config, &workspace, &cwd, &request).decision(), PermissionRuleDecision::Ask);
849    }
850
851    #[test]
852    fn relative_paths_resolve_from_current_directory() {
853        let (_temp, workspace, cwd) = workspace_roots();
854        let config = PermissionsConfig {
855            ask: vec!["Read(./nested-file.rs)".to_string()],
856            ..PermissionsConfig::default()
857        };
858        let request = build_permission_request(&workspace, &cwd, "read_file", Some(&json!({"path": "nested-file.rs"})));
859
860        assert_eq!(evaluate_permissions(&config, &workspace, &cwd, &request).decision(), PermissionRuleDecision::Ask);
861    }
862
863    #[test]
864    fn exact_tool_rules_feed_rule_tiers() {
865        let (_temp, workspace, cwd) = workspace_roots();
866        // Use semantic rules which are the recommended approach
867        let config = PermissionsConfig {
868            allow: vec!["read".to_string()],
869            deny: vec!["bash".to_string()],
870            ..PermissionsConfig::default()
871        };
872
873        let read_request = PermissionRequest {
874            exact_tool_name: "read_file".to_string(),
875            kind: PermissionRequestKind::Read { paths: vec![] },
876            builtin_file_mutation: false,
877            protected_write_paths: Vec::new(),
878        };
879        let exec_request = PermissionRequest {
880            exact_tool_name: "command_session".to_string(),
881            kind: PermissionRequestKind::Bash { command: "test".to_string() },
882            builtin_file_mutation: false,
883            protected_write_paths: Vec::new(),
884        };
885
886        assert!(evaluate_permissions(&config, &workspace, &cwd, &read_request).allow);
887        assert!(evaluate_permissions(&config, &workspace, &cwd, &exec_request).deny);
888    }
889
890    #[test]
891    fn agent_deny_wins_over_ask_auto_allow_and_default() {
892        let (_temp, workspace, cwd) = workspace_roots();
893        // Use a custom tool name that won't be normalized to a semantic rule
894        let request = exact_tool_request("custom_tool");
895        let mut permissions = agent_permissions(PermissionDefault::Allow);
896        permissions.allow = vec!["custom_tool".to_string()];
897        permissions.auto = vec!["custom_tool".to_string()];
898        permissions.ask = vec!["custom_tool".to_string()];
899        permissions.deny = vec!["custom_tool".to_string()];
900
901        assert_eq!(
902            evaluate_agent_permissions(&permissions, &workspace, &cwd, &request),
903            ResolvedPermissionDecision::Deny
904        );
905    }
906
907    #[test]
908    fn agent_ask_wins_over_auto_allow_and_default() {
909        let (_temp, workspace, cwd) = workspace_roots();
910        // Use a custom tool name that won't be normalized to a semantic rule
911        let request = exact_tool_request("custom_tool");
912        let mut permissions = agent_permissions(PermissionDefault::Deny);
913        permissions.allow = vec!["custom_tool".to_string()];
914        permissions.auto = vec!["custom_tool".to_string()];
915        permissions.ask = vec!["custom_tool".to_string()];
916
917        assert_eq!(
918            evaluate_agent_permissions(&permissions, &workspace, &cwd, &request),
919            ResolvedPermissionDecision::Ask
920        );
921    }
922
923    #[test]
924    fn agent_auto_wins_over_allow_and_default() {
925        let (_temp, workspace, cwd) = workspace_roots();
926        // Use a custom tool name that won't be normalized to a semantic rule
927        let request = exact_tool_request("custom_tool");
928        let mut permissions = agent_permissions(PermissionDefault::Deny);
929        permissions.allow = vec!["custom_tool".to_string()];
930        permissions.auto = vec!["custom_tool".to_string()];
931
932        assert_eq!(
933            evaluate_agent_permissions(&permissions, &workspace, &cwd, &request),
934            ResolvedPermissionDecision::Auto
935        );
936    }
937
938    #[test]
939    fn agent_allow_wins_over_default() {
940        let (_temp, workspace, cwd) = workspace_roots();
941        // Use a custom tool name that won't be normalized to a semantic rule
942        let request = exact_tool_request("custom_tool");
943        let mut permissions = agent_permissions(PermissionDefault::Deny);
944        permissions.allow = vec!["custom_tool".to_string()];
945
946        assert_eq!(
947            evaluate_agent_permissions(&permissions, &workspace, &cwd, &request),
948            ResolvedPermissionDecision::Allow
949        );
950    }
951
952    #[test]
953    fn agent_read_permission_allows_file_operation_read_only() {
954        let (_temp, workspace, cwd) = workspace_roots();
955        let mut permissions = agent_permissions(PermissionDefault::Deny);
956        permissions.allow = vec!["read".to_string()];
957
958        let read_request = build_permission_request(
959            &workspace,
960            &cwd,
961            tools::UNIFIED_FILE,
962            Some(&json!({"action": "read", "path": "README.md"})),
963        );
964        let write_request = build_permission_request(
965            &workspace,
966            &cwd,
967            tools::UNIFIED_FILE,
968            Some(&json!({"action": "write", "path": "README.md", "content": "x"})),
969        );
970
971        assert_eq!(
972            evaluate_agent_permissions(&permissions, &workspace, &cwd, &read_request),
973            ResolvedPermissionDecision::Allow
974        );
975        assert_eq!(
976            evaluate_agent_permissions(&permissions, &workspace, &cwd, &write_request),
977            ResolvedPermissionDecision::Deny
978        );
979    }
980
981    #[test]
982    fn agent_read_permission_allows_code_search_but_not_exec_command() {
983        let (_temp, workspace, cwd) = workspace_roots();
984        let mut permissions = agent_permissions(PermissionDefault::Deny);
985        permissions.allow = vec!["Read".to_string()];
986
987        let code_search = build_permission_request(
988            &workspace,
989            &cwd,
990            tools::CODE_SEARCH,
991            Some(&json!({"query": "PermissionRequest"})),
992        );
993        let exec_command =
994            build_permission_request(&workspace, &cwd, tools::EXEC_COMMAND, Some(&json!({"cmd": "rg --files"})));
995
996        assert!(matches!(code_search.kind, PermissionRequestKind::Read { .. }));
997        assert_eq!(exec_command.kind, PermissionRequestKind::Bash { command: "rg --files".to_string() });
998        assert_eq!(
999            evaluate_agent_permissions(&permissions, &workspace, &cwd, &code_search),
1000            ResolvedPermissionDecision::Allow
1001        );
1002        assert_eq!(
1003            evaluate_agent_permissions(&permissions, &workspace, &cwd, &exec_command),
1004            ResolvedPermissionDecision::Deny
1005        );
1006    }
1007
1008    #[test]
1009    fn dry_run_exec_command_remains_bash_under_read_only_permissions() {
1010        let (_temp, workspace, cwd) = workspace_roots();
1011        let mut permissions = agent_permissions(PermissionDefault::Deny);
1012        permissions.allow = vec!["Read".to_string()];
1013        let request = build_permission_request(
1014            &workspace,
1015            &cwd,
1016            tools::EXEC_COMMAND,
1017            Some(&json!({"cmd": "python mutate.py --dry-run"})),
1018        );
1019
1020        assert_eq!(request.kind, PermissionRequestKind::Bash { command: "python mutate.py --dry-run".to_string() });
1021        assert_eq!(
1022            evaluate_agent_permissions(&permissions, &workspace, &cwd, &request),
1023            ResolvedPermissionDecision::Deny
1024        );
1025    }
1026
1027    #[test]
1028    fn exec_command_advertisement_uses_bash_permission() {
1029        let (_temp, workspace, cwd) = workspace_roots();
1030        let requests = build_advertised_permission_requests(&workspace, &cwd, tools::EXEC_COMMAND);
1031
1032        assert_eq!(requests.len(), 1);
1033        assert_eq!(requests[0].kind, PermissionRequestKind::Bash { command: "rg --files".to_string() });
1034    }
1035
1036    #[test]
1037    fn public_read_requests_preserve_global_deny_and_ask_precedence() {
1038        let (_temp, workspace, cwd) = workspace_roots();
1039        let request = build_permission_request(
1040            &workspace,
1041            &cwd,
1042            tools::CODE_SEARCH,
1043            Some(&json!({"query": "PermissionRequest"})),
1044        );
1045        let mut permissions = agent_permissions(PermissionDefault::Deny);
1046        permissions.allow = vec!["Read".to_string()];
1047
1048        let deny = PermissionsConfig {
1049            deny: vec!["Read".to_string()],
1050            ..PermissionsConfig::default()
1051        };
1052        assert_eq!(
1053            evaluate_effective_permissions(&deny, &permissions, &workspace, &cwd, &request),
1054            ResolvedPermissionDecision::Deny
1055        );
1056
1057        let ask = PermissionsConfig {
1058            ask: vec!["Read".to_string()],
1059            ..PermissionsConfig::default()
1060        };
1061        assert_eq!(
1062            evaluate_effective_permissions(&ask, &permissions, &workspace, &cwd, &request),
1063            ResolvedPermissionDecision::Ask
1064        );
1065    }
1066
1067    #[test]
1068    fn explicit_bash_rules_continue_to_govern_mutating_exec_command() {
1069        let (_temp, workspace, cwd) = workspace_roots();
1070        let request = build_permission_request(
1071            &workspace,
1072            &cwd,
1073            tools::EXEC_COMMAND,
1074            Some(&json!({"cmd": "printf changed > file.txt"})),
1075        );
1076        let mut permissions = agent_permissions(PermissionDefault::Deny);
1077        permissions.allow = vec!["Bash(printf changed*)".to_string()];
1078
1079        assert_eq!(
1080            evaluate_agent_permissions(&permissions, &workspace, &cwd, &request),
1081            ResolvedPermissionDecision::Allow
1082        );
1083
1084        let global = PermissionsConfig {
1085            deny: vec!["Bash(printf changed*)".to_string()],
1086            ..PermissionsConfig::default()
1087        };
1088        assert_eq!(
1089            evaluate_effective_permissions(&global, &permissions, &workspace, &cwd, &request),
1090            ResolvedPermissionDecision::Deny
1091        );
1092    }
1093
1094    #[test]
1095    fn unmatched_agent_calls_use_permissions_default() {
1096        let (_temp, workspace, cwd) = workspace_roots();
1097        let request = exact_tool_request("read_file");
1098        let permissions = agent_permissions(PermissionDefault::Auto);
1099
1100        assert_eq!(
1101            evaluate_agent_permissions(&permissions, &workspace, &cwd, &request),
1102            ResolvedPermissionDecision::Auto
1103        );
1104    }
1105
1106    #[test]
1107    fn missing_permissions_default_is_invalid_before_evaluation() {
1108        let err = toml::from_str::<AgentPermissionsConfig>(r#"allow = ["read_file"]"#).unwrap_err();
1109
1110        assert!(err.to_string().contains("missing field `default`"));
1111    }
1112
1113    #[test]
1114    fn global_deny_is_hard_ceiling() {
1115        let (_temp, workspace, cwd) = workspace_roots();
1116        // Use a custom tool name that won't be normalized to a semantic rule
1117        let request = exact_tool_request("custom_tool");
1118        let global = PermissionsConfig {
1119            deny: vec!["custom_tool".to_string()],
1120            ..PermissionsConfig::default()
1121        };
1122        let permissions = agent_permissions(PermissionDefault::Allow);
1123
1124        assert_eq!(
1125            evaluate_effective_permissions(&global, &permissions, &workspace, &cwd, &request),
1126            ResolvedPermissionDecision::Deny
1127        );
1128    }
1129
1130    #[test]
1131    fn global_ask_forces_prompt_over_agent_allow_or_auto() {
1132        let (_temp, workspace, cwd) = workspace_roots();
1133        // Use a custom tool name that won't be normalized to a semantic rule
1134        let request = exact_tool_request("custom_tool");
1135        let global = PermissionsConfig {
1136            ask: vec!["custom_tool".to_string()],
1137            ..PermissionsConfig::default()
1138        };
1139
1140        assert_eq!(
1141            evaluate_effective_permissions(
1142                &global,
1143                &agent_permissions(PermissionDefault::Allow),
1144                &workspace,
1145                &cwd,
1146                &request,
1147            ),
1148            ResolvedPermissionDecision::Ask
1149        );
1150        assert_eq!(
1151            evaluate_effective_permissions(
1152                &global,
1153                &agent_permissions(PermissionDefault::Auto),
1154                &workspace,
1155                &cwd,
1156                &request,
1157            ),
1158            ResolvedPermissionDecision::Ask
1159        );
1160    }
1161
1162    #[test]
1163    fn global_allow_cannot_override_agent_deny_or_auto() {
1164        let (_temp, workspace, cwd) = workspace_roots();
1165        let request = exact_tool_request("command_session");
1166        let global = PermissionsConfig {
1167            allow: vec!["command_session".to_string()],
1168            ..PermissionsConfig::default()
1169        };
1170
1171        assert_eq!(
1172            evaluate_effective_permissions(
1173                &global,
1174                &agent_permissions(PermissionDefault::Deny),
1175                &workspace,
1176                &cwd,
1177                &request,
1178            ),
1179            ResolvedPermissionDecision::Deny
1180        );
1181        assert_eq!(
1182            evaluate_effective_permissions(
1183                &global,
1184                &agent_permissions(PermissionDefault::Auto),
1185                &workspace,
1186                &cwd,
1187                &request,
1188            ),
1189            ResolvedPermissionDecision::Auto
1190        );
1191    }
1192
1193    #[test]
1194    fn agent_specific_deny_wins_within_agent_scope() {
1195        let (_temp, workspace, cwd) = workspace_roots();
1196        // Use a custom tool name that won't be normalized to a semantic rule
1197        let request = exact_tool_request("custom_tool");
1198        let global = PermissionsConfig {
1199            allow: vec!["custom_tool".to_string()],
1200            ..PermissionsConfig::default()
1201        };
1202        let mut permissions = agent_permissions(PermissionDefault::Allow);
1203        permissions.deny = vec!["custom_tool".to_string()];
1204
1205        assert_eq!(
1206            evaluate_effective_permissions(&global, &permissions, &workspace, &cwd, &request),
1207            ResolvedPermissionDecision::Deny
1208        );
1209    }
1210
1211    #[test]
1212    fn auto_bucket_resolves_to_classifier_backed_decision() {
1213        let (_temp, workspace, cwd) = workspace_roots();
1214        // Use a custom tool name that won't be normalized to a semantic rule
1215        let request = exact_tool_request("custom_tool");
1216        let mut permissions = agent_permissions(PermissionDefault::Ask);
1217        permissions.auto = vec!["custom_tool".to_string()];
1218
1219        assert_eq!(
1220            evaluate_agent_permissions(&permissions, &workspace, &cwd, &request),
1221            ResolvedPermissionDecision::Auto
1222        );
1223    }
1224
1225    /// Turn_912/913 regression: the built-in plan agent's permission rules
1226    /// must keep every tool in the planning wire catalog visible — the wire
1227    /// shaper hides a tool only when ALL advertised permission requests are
1228    /// denied, and the old read-only allow list denied `exec_command` (Bash)
1229    /// and `request_user_input` (Other), collapsing the planning catalog to
1230    /// bare `code_search`. Mutation tools must stay fully denied.
1231    #[test]
1232    fn builtin_plan_agent_keeps_planning_catalog_wire_visible() {
1233        let (_temp, workspace, cwd) = workspace_roots();
1234        let global = PermissionsConfig::default();
1235        let plan = vtcode_config::builtin_plan_agent();
1236
1237        for tool in [
1238            tools::EXEC_COMMAND,
1239            tools::CODE_SEARCH,
1240            tools::GREP_FILE,
1241            tools::READ_FILE,
1242            tools::LIST_FILES,
1243            tools::REQUEST_USER_INPUT,
1244            tools::RECORD_DECISION,
1245        ] {
1246            let requests = build_advertised_permission_requests(&workspace, &cwd, tool);
1247            assert!(!requests.is_empty(), "{tool} must advertise at least one permission request");
1248            let any_allowed = requests.iter().any(|request| {
1249                evaluate_effective_permissions(&global, &plan.permissions, &workspace, &cwd, request)
1250                    != ResolvedPermissionDecision::Deny
1251            });
1252            assert!(any_allowed, "{tool} must survive wire shaping for the plan agent");
1253        }
1254
1255        for tool in [tools::APPLY_PATCH, tools::WRITE_FILE, tools::EDIT_FILE] {
1256            let requests = build_advertised_permission_requests(&workspace, &cwd, tool);
1257            let all_denied = requests.iter().all(|request| {
1258                evaluate_effective_permissions(&global, &plan.permissions, &workspace, &cwd, request)
1259                    == ResolvedPermissionDecision::Deny
1260            });
1261            assert!(all_denied, "{tool} must stay hidden from the plan agent");
1262        }
1263    }
1264}