Skip to main content

vtcode_core/permissions/
mod.rs

1use glob::Pattern;
2use ignore::gitignore::{Gitignore, GitignoreBuilder};
3use serde_json::{Value, json};
4use std::path::{Path, PathBuf};
5use tracing::warn;
6use url::Url;
7
8use crate::config::PermissionsConfig;
9use crate::config::constants::tools;
10use crate::tools::command_args;
11use crate::tools::mcp::{MCP_QUALIFIED_TOOL_PREFIX, legacy_mcp_tool_name, parse_canonical_mcp_tool_name};
12use crate::tools::tool_intent;
13use vtcode_config::core::permissions::{AgentPermissionsConfig, PermissionDefault, normalize_permission_rule};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16#[must_use = "permission decisions must be enforced"]
17pub enum PermissionRuleDecision {
18    Allow,
19    Auto,
20    Ask,
21    Deny,
22    NoMatch,
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26#[must_use = "permission decisions must be enforced"]
27pub enum ResolvedPermissionDecision {
28    Allow,
29    Auto,
30    Ask,
31    Deny,
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
35pub struct PermissionRuleMatches {
36    pub deny: bool,
37    pub ask: bool,
38    pub auto: bool,
39    pub allow: bool,
40}
41
42impl PermissionRuleMatches {
43    /// Converts these matches into a single [`PermissionRuleDecision`] using deny > ask > auto > allow precedence.
44    pub const fn decision(self) -> PermissionRuleDecision {
45        if self.deny {
46            PermissionRuleDecision::Deny
47        } else if self.ask {
48            PermissionRuleDecision::Ask
49        } else if self.auto {
50            PermissionRuleDecision::Auto
51        } else if self.allow {
52            PermissionRuleDecision::Allow
53        } else {
54            PermissionRuleDecision::NoMatch
55        }
56    }
57}
58
59/// Categorizes a permission request by the type of operation being performed.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum PermissionRequestKind {
62    /// A shell command execution request.
63    Bash { command: String },
64    /// A file read request targeting the given paths.
65    Read { paths: Vec<PathBuf> },
66    /// A file edit request targeting the given paths.
67    Edit { paths: Vec<PathBuf> },
68    /// A file write/create/delete request targeting the given paths.
69    Write { paths: Vec<PathBuf> },
70    /// A web fetch request targeting the given domains.
71    WebFetch { domains: Vec<String> },
72    /// An MCP tool invocation for the given server and tool.
73    Mcp { server: String, tool: String },
74    /// A tool call that does not fit the categories above.
75    Other,
76}
77
78/// A fully described permission request carrying the tool name, operation kind,
79/// and any protected-path metadata needed for prompting.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct PermissionRequest {
82    /// Exact (normalized) tool name that originated this request.
83    pub exact_tool_name: String,
84    /// Categorized operation kind for rule matching.
85    pub kind: PermissionRequestKind,
86    /// Whether this request mutates a file via a builtin file tool.
87    pub builtin_file_mutation: bool,
88    /// Paths within protected directories (`.git`, `.vtcode`, etc.) that require extra confirmation.
89    pub protected_write_paths: Vec<PathBuf>,
90}
91
92impl PermissionRequest {
93    /// Returns `true` if this request targets one or more protected write paths.
94    pub fn requires_protected_write_prompt(&self) -> bool {
95        !self.protected_write_paths.is_empty()
96    }
97}
98
99/// Constructs a [`PermissionRequest`] from a normalized tool name and its arguments.
100pub fn build_permission_request(
101    workspace_root: &Path,
102    current_dir: &Path,
103    normalized_tool_name: &str,
104    tool_args: Option<&Value>,
105) -> PermissionRequest {
106    let kind = build_request_kind(workspace_root, current_dir, normalized_tool_name, tool_args);
107    let protected_write_paths = protected_write_paths(workspace_root, &kind);
108    let builtin_file_mutation =
109        matches!(kind, PermissionRequestKind::Edit { .. } | PermissionRequestKind::Write { .. });
110
111    PermissionRequest {
112        exact_tool_name: normalized_tool_name.to_string(),
113        kind,
114        builtin_file_mutation,
115        protected_write_paths,
116    }
117}
118
119/// Build representative permission requests for advertised tool availability.
120///
121/// Runtime dispatch still evaluates the concrete call arguments. Advertisement cannot know future
122/// arguments, so multi-action tools include each category they can expose and callers should treat
123/// any denied representative request as a reason not to grant provider-native availability.
124pub fn build_advertised_permission_requests(
125    workspace_root: &Path,
126    current_dir: &Path,
127    normalized_tool_name: &str,
128) -> Vec<PermissionRequest> {
129    let representative_args = advertised_permission_args(normalized_tool_name);
130    if representative_args.is_empty() {
131        return vec![build_permission_request(
132            workspace_root,
133            current_dir,
134            normalized_tool_name,
135            None,
136        )];
137    }
138
139    representative_args
140        .iter()
141        .map(|args| build_permission_request(workspace_root, current_dir, normalized_tool_name, Some(args)))
142        .collect()
143}
144
145/// Evaluates a permission request against the global permission configuration and
146/// returns which rule tiers matched.
147pub fn evaluate_permissions(
148    config: &PermissionsConfig,
149    workspace_root: &Path,
150    current_dir: &Path,
151    request: &PermissionRequest,
152) -> PermissionRuleMatches {
153    let evaluator = PermissionRuleSet::from_global_config(config, workspace_root, current_dir);
154    evaluator.evaluate_matches(request)
155}
156
157/// Evaluates a permission request against an agent's permission configuration,
158/// returning the resolved decision using the agent's default when no rule matches.
159pub fn evaluate_agent_permissions(
160    agent_permissions: &AgentPermissionsConfig,
161    workspace_root: &Path,
162    current_dir: &Path,
163    request: &PermissionRequest,
164) -> ResolvedPermissionDecision {
165    let evaluator = PermissionRuleSet::from_agent_config(agent_permissions, workspace_root, current_dir);
166    evaluator.resolve(request, agent_permissions.default)
167}
168
169/// Evaluates a permission request by combining global and agent-level rules.
170/// Global deny is a hard ceiling; global ask forces a prompt unless the agent denies.
171pub fn evaluate_effective_permissions(
172    global_config: &PermissionsConfig,
173    agent_permissions: &AgentPermissionsConfig,
174    workspace_root: &Path,
175    current_dir: &Path,
176    request: &PermissionRequest,
177) -> ResolvedPermissionDecision {
178    let global = PermissionRuleSet::from_global_config(global_config, workspace_root, current_dir);
179    let global_matches = global.evaluate_matches(request);
180    if global_matches.deny {
181        return ResolvedPermissionDecision::Deny;
182    }
183
184    let agent_decision = evaluate_agent_permissions(agent_permissions, workspace_root, current_dir, request);
185    if global_matches.ask && agent_decision != ResolvedPermissionDecision::Deny {
186        return ResolvedPermissionDecision::Ask;
187    }
188
189    agent_decision
190}
191
192struct PermissionRuleSet {
193    deny: Vec<CompiledPermissionRule>,
194    ask: Vec<CompiledPermissionRule>,
195    auto: Vec<CompiledPermissionRule>,
196    allow: Vec<CompiledPermissionRule>,
197}
198
199impl PermissionRuleSet {
200    fn from_global_config(config: &PermissionsConfig, workspace_root: &Path, current_dir: &Path) -> Self {
201        Self {
202            deny: compile_rules(&config.deny, workspace_root, current_dir),
203            ask: compile_rules(&config.ask, workspace_root, current_dir),
204            auto: Vec::new(),
205            allow: compile_rules(&config.allow, workspace_root, current_dir),
206        }
207    }
208
209    fn from_agent_config(config: &AgentPermissionsConfig, workspace_root: &Path, current_dir: &Path) -> Self {
210        Self {
211            deny: compile_rules(&config.deny, workspace_root, current_dir),
212            ask: compile_rules(&config.ask, workspace_root, current_dir),
213            auto: compile_rules(&config.auto, workspace_root, current_dir),
214            allow: compile_rules(&config.allow, workspace_root, current_dir),
215        }
216    }
217
218    fn evaluate_matches(&self, request: &PermissionRequest) -> PermissionRuleMatches {
219        PermissionRuleMatches {
220            deny: self.deny.iter().any(|rule| rule.matches(request)),
221            ask: self.ask.iter().any(|rule| rule.matches(request)),
222            auto: self.auto.iter().any(|rule| rule.matches(request)),
223            allow: self.allow.iter().any(|rule| rule.matches(request)),
224        }
225    }
226
227    fn resolve(&self, request: &PermissionRequest, default: PermissionDefault) -> ResolvedPermissionDecision {
228        let matches = self.evaluate_matches(request);
229        if matches.deny {
230            ResolvedPermissionDecision::Deny
231        } else if matches.ask {
232            ResolvedPermissionDecision::Ask
233        } else if matches.auto {
234            ResolvedPermissionDecision::Auto
235        } else if matches.allow {
236            ResolvedPermissionDecision::Allow
237        } else {
238            default.into()
239        }
240    }
241}
242
243impl From<PermissionDefault> for ResolvedPermissionDecision {
244    fn from(default: PermissionDefault) -> Self {
245        match default {
246            PermissionDefault::Ask => Self::Ask,
247            PermissionDefault::Allow => Self::Allow,
248            PermissionDefault::Auto => Self::Auto,
249            PermissionDefault::Deny => Self::Deny,
250        }
251    }
252}
253
254fn compile_rules(rules: &[String], workspace_root: &Path, current_dir: &Path) -> Vec<CompiledPermissionRule> {
255    rules
256        .iter()
257        .filter_map(|rule| {
258            let compiled = CompiledPermissionRule::compile(rule, workspace_root, current_dir);
259            if compiled.is_none() {
260                // A rule that compiles to nothing silently enforces nothing;
261                // say so loudly, since a typo here usually means a missing deny.
262                warn!("Ignoring unparseable permission rule: {rule}");
263            }
264            compiled
265        })
266        .collect()
267}
268
269#[derive(Debug)]
270enum CompiledPermissionRule {
271    Bash(Option<Pattern>),
272    Read(Option<PathRuleMatcher>),
273    Edit(Option<PathRuleMatcher>),
274    Write(Option<PathRuleMatcher>),
275    WebFetchAll,
276    WebFetchDomain(String),
277    McpServer(String),
278    McpWildcard(String),
279    McpTool { server: String, tool: String },
280    ExactTool(String),
281}
282
283impl CompiledPermissionRule {
284    fn compile(raw: &str, workspace_root: &Path, current_dir: &Path) -> Option<Self> {
285        let rule = normalize_permission_rule(raw);
286        let rule = rule.trim();
287        if rule.is_empty() {
288            return None;
289        }
290
291        if rule.eq_ignore_ascii_case("bash") || rule.eq_ignore_ascii_case("bash(*)") {
292            return Some(Self::Bash(None));
293        }
294        if let Some(specifier) = parse_tool_specifier(rule, "bash") {
295            return compile_bash_rule(specifier).map(Self::Bash);
296        }
297
298        if rule.eq_ignore_ascii_case("read") || rule.eq_ignore_ascii_case("read(*)") {
299            return Some(Self::Read(None));
300        }
301        if let Some(specifier) = parse_tool_specifier(rule, "read") {
302            return PathRuleMatcher::compile(specifier, workspace_root, current_dir)
303                .map(Some)
304                .map(Self::Read);
305        }
306
307        if rule.eq_ignore_ascii_case("edit") || rule.eq_ignore_ascii_case("edit(*)") {
308            return Some(Self::Edit(None));
309        }
310        if let Some(specifier) = parse_tool_specifier(rule, "edit") {
311            return PathRuleMatcher::compile(specifier, workspace_root, current_dir)
312                .map(Some)
313                .map(Self::Edit);
314        }
315
316        if rule.eq_ignore_ascii_case("write") || rule.eq_ignore_ascii_case("write(*)") {
317            return Some(Self::Write(None));
318        }
319        if let Some(specifier) = parse_tool_specifier(rule, "write") {
320            return PathRuleMatcher::compile(specifier, workspace_root, current_dir)
321                .map(Some)
322                .map(Self::Write);
323        }
324
325        if rule.eq_ignore_ascii_case("webfetch") || rule.eq_ignore_ascii_case("webfetch(*)") {
326            return Some(Self::WebFetchAll);
327        }
328        if let Some(specifier) = parse_tool_specifier(rule, "webfetch") {
329            let domain = specifier.strip_prefix("domain:")?.trim().to_ascii_lowercase();
330            if domain.is_empty() {
331                return None;
332            }
333            return Some(Self::WebFetchDomain(domain));
334        }
335
336        if let Some(server) = rule.strip_prefix(MCP_QUALIFIED_TOOL_PREFIX) {
337            if let Some((server, tool)) = server.split_once("__") {
338                if tool == "*" {
339                    return Some(Self::McpWildcard(server.to_string()));
340                }
341                if !server.is_empty() && !tool.is_empty() {
342                    return Some(Self::McpTool { server: server.to_string(), tool: tool.to_string() });
343                }
344                return None;
345            }
346            if !server.is_empty() {
347                return Some(Self::McpServer(server.to_string()));
348            }
349            return None;
350        }
351
352        if rule.contains('(') || rule.contains(')') {
353            return None;
354        }
355
356        Some(Self::ExactTool(rule.to_string()))
357    }
358
359    fn matches(&self, request: &PermissionRequest) -> bool {
360        match self {
361            Self::Bash(pattern) => match &request.kind {
362                PermissionRequestKind::Bash { command } => {
363                    pattern.as_ref().is_none_or(|pattern| pattern.matches(command))
364                }
365                _ => false,
366            },
367            Self::Read(matcher) => match &request.kind {
368                PermissionRequestKind::Read { paths } => matcher
369                    .as_ref()
370                    .is_none_or(|matcher| paths.iter().any(|path| matcher.matches(path))),
371                _ => false,
372            },
373            Self::Edit(matcher) => match &request.kind {
374                PermissionRequestKind::Edit { paths } => matcher
375                    .as_ref()
376                    .is_none_or(|matcher| paths.iter().any(|path| matcher.matches(path))),
377                _ => false,
378            },
379            Self::Write(matcher) => match &request.kind {
380                PermissionRequestKind::Write { paths } => matcher
381                    .as_ref()
382                    .is_none_or(|matcher| paths.iter().any(|path| matcher.matches(path))),
383                _ => false,
384            },
385            Self::WebFetchAll => matches!(request.kind, PermissionRequestKind::WebFetch { .. }),
386            Self::WebFetchDomain(domain) => match &request.kind {
387                PermissionRequestKind::WebFetch { domains } => {
388                    domains.iter().any(|candidate| domain_matches_allowed(candidate, domain))
389                }
390                _ => false,
391            },
392            Self::McpServer(server) | Self::McpWildcard(server) => match &request.kind {
393                PermissionRequestKind::Mcp { server: candidate, tool } => {
394                    candidate == server
395                        || (tool.is_empty()
396                            && candidate
397                                .strip_prefix(server.as_str())
398                                .is_some_and(|rest| rest.starts_with('_')))
399                }
400                _ => false,
401            },
402            Self::McpTool { server, tool } => match &request.kind {
403                PermissionRequestKind::Mcp { server: candidate_server, tool: candidate_tool } => {
404                    candidate_server == server && candidate_tool == tool
405                }
406                _ => false,
407            },
408            Self::ExactTool(tool_name) => request.exact_tool_name == *tool_name,
409        }
410    }
411}
412
413fn parse_tool_specifier<'a>(rule: &'a str, tool_name: &str) -> Option<&'a str> {
414    let open = rule.find('(')?;
415    let close = rule.rfind(')')?;
416    if close <= open || close + 1 != rule.len() {
417        return None;
418    }
419    let prefix = &rule[..open];
420    prefix.eq_ignore_ascii_case(tool_name).then_some(rule[open + 1..close].trim())
421}
422
423fn compile_bash_rule(specifier: &str) -> Option<Option<Pattern>> {
424    if specifier.is_empty() || specifier == "*" {
425        return Some(None);
426    }
427    Pattern::new(specifier).ok().map(Some)
428}
429
430#[derive(Debug)]
431struct PathRuleMatcher {
432    matcher: Gitignore,
433}
434
435impl PathRuleMatcher {
436    fn compile(raw: &str, workspace_root: &Path, current_dir: &Path) -> Option<Self> {
437        let home_dir = dirs::home_dir();
438        let (root, pattern) = if let Some(path) = raw.strip_prefix("//") {
439            (PathBuf::from("/"), format!("/{path}"))
440        } else if let Some(path) = raw.strip_prefix("~/") {
441            (home_dir?, format!("/{path}"))
442        } else if raw.starts_with('/') {
443            (workspace_root.to_path_buf(), raw.to_string())
444        } else if let Some(path) = raw.strip_prefix("./") {
445            (current_dir.to_path_buf(), path.to_string())
446        } else {
447            (current_dir.to_path_buf(), raw.to_string())
448        };
449
450        let mut builder = GitignoreBuilder::new(root);
451        builder.add_line(None, &pattern).ok()?;
452        let matcher = builder.build().ok()?;
453        Some(Self { matcher })
454    }
455
456    fn matches(&self, candidate: &Path) -> bool {
457        self.matcher.matched_path_or_any_parents(candidate, false).is_ignore()
458    }
459}
460
461fn build_request_kind(
462    workspace_root: &Path,
463    current_dir: &Path,
464    normalized_tool_name: &str,
465    tool_args: Option<&Value>,
466) -> PermissionRequestKind {
467    if let Some((server, tool)) = parse_mcp_request(normalized_tool_name) {
468        return PermissionRequestKind::Mcp { server, tool };
469    }
470
471    if normalized_tool_name == tools::CODE_SEARCH {
472        let paths = tool_args.map_or_else(Vec::new, |args| {
473            extract_candidate_paths(workspace_root, current_dir, normalized_tool_name, args)
474        });
475        return PermissionRequestKind::Read { paths };
476    }
477
478    let Some(args) = tool_args else {
479        return PermissionRequestKind::Other;
480    };
481
482    if normalized_tool_name == tools::EXEC_COMMAND {
483        let command = command_args::command_text(args).ok().flatten().unwrap_or_default();
484        return PermissionRequestKind::Bash { command };
485    }
486
487    if tool_intent::is_command_run_tool_call(normalized_tool_name, args)
488        && let Ok(Some(command)) = command_args::command_text(args)
489    {
490        return PermissionRequestKind::Bash { command };
491    }
492
493    if is_web_fetch_request(normalized_tool_name, args) {
494        let domains = extract_web_domains(args);
495        return PermissionRequestKind::WebFetch { domains };
496    }
497
498    if let Some(kind) = file_request_kind(workspace_root, current_dir, normalized_tool_name, args) {
499        return kind;
500    }
501
502    PermissionRequestKind::Other
503}
504
505fn advertised_permission_args(normalized_tool_name: &str) -> Vec<Value> {
506    match normalized_tool_name {
507        tools::UNIFIED_EXEC | tools::EXEC_PTY_CMD | "exec" => {
508            vec![json!({ "action": "run", "command": "true" })]
509        }
510        tools::EXEC_COMMAND => vec![json!({ "cmd": "rg --files" })],
511        tools::RUN_PTY_CMD | tools::CREATE_PTY_SESSION | tools::SHELL | "bash" => {
512            vec![json!({ "command": "true" })]
513        }
514        tools::READ_FILE | tools::GREP_FILE | tools::LIST_FILES => {
515            vec![json!({ "path": "." })]
516        }
517        tools::CODE_SEARCH => vec![json!({ "query": "probe", "path": "." })],
518        tools::WRITE_FILE | tools::CREATE_FILE | tools::DELETE_FILE => {
519            vec![json!({ "path": "advertised-permission-probe.txt" })]
520        }
521        tools::MOVE_FILE | tools::COPY_FILE => vec![json!({
522            "path": "advertised-permission-probe.txt",
523            "destination": "advertised-permission-probe-copy.txt"
524        })],
525        tools::EDIT_FILE | tools::SEARCH_REPLACE => {
526            vec![json!({ "path": "advertised-permission-probe.txt" })]
527        }
528        tools::APPLY_PATCH => vec![json!({
529            "patch": "*** Begin Patch\n*** Update File: advertised-permission-probe.txt\n@@\n-old\n+new\n*** End Patch\n"
530        })],
531        tools::FILE_OP => vec![json!({ "path": "advertised-permission-probe.txt" })],
532        tools::UNIFIED_FILE => vec![
533            json!({ "action": "read", "path": "." }),
534            json!({ "action": "edit", "path": "advertised-permission-probe.txt" }),
535            json!({ "action": "write", "path": "advertised-permission-probe.txt" }),
536        ],
537        tools::WEB_FETCH | tools::FETCH_URL => vec![json!({ "url": "https://example.com/" })],
538        _ => Vec::new(),
539    }
540}
541
542fn parse_mcp_request(normalized_tool_name: &str) -> Option<(String, String)> {
543    if let Some((server, tool)) = parse_canonical_mcp_tool_name(normalized_tool_name) {
544        return Some((server.to_string(), tool.to_string()));
545    }
546
547    if let Some((server, tool)) = parse_qualified_mcp_tool_name(normalized_tool_name) {
548        return Some((server.to_string(), tool.to_string()));
549    }
550
551    // Legacy `mcp_<provider>_<tool>` names carry no provider/tool delimiter,
552    // so the server is ambiguous. Report the whole remainder with an empty
553    // tool: server rules match it by prefix (fail-closed), exact tool rules
554    // cannot match it.
555    legacy_mcp_tool_name(normalized_tool_name).map(|remainder| (remainder.to_string(), String::new()))
556}
557
558fn parse_qualified_mcp_tool_name(normalized_tool_name: &str) -> Option<(&str, &str)> {
559    let stripped = normalized_tool_name.strip_prefix(MCP_QUALIFIED_TOOL_PREFIX)?;
560    let (server, tool) = stripped.split_once("__")?;
561    if server.is_empty() || tool.is_empty() || tool == "*" {
562        return None;
563    }
564    Some((server, tool))
565}
566
567fn is_web_fetch_request(normalized_tool_name: &str, _args: &Value) -> bool {
568    normalized_tool_name == tools::WEB_FETCH || normalized_tool_name == tools::FETCH_URL
569}
570
571fn file_request_kind(
572    workspace_root: &Path,
573    current_dir: &Path,
574    normalized_tool_name: &str,
575    args: &Value,
576) -> Option<PermissionRequestKind> {
577    let paths = extract_candidate_paths(workspace_root, current_dir, normalized_tool_name, args);
578
579    match normalized_tool_name {
580        tools::READ_FILE | tools::GREP_FILE | tools::LIST_FILES | tools::CODE_SEARCH => {
581            Some(PermissionRequestKind::Read { paths })
582        }
583        tools::WRITE_FILE | tools::CREATE_FILE | tools::DELETE_FILE | tools::MOVE_FILE | tools::COPY_FILE => {
584            Some(PermissionRequestKind::Write { paths })
585        }
586        tools::EDIT_FILE | tools::APPLY_PATCH | tools::SEARCH_REPLACE | tools::FILE_OP => {
587            Some(PermissionRequestKind::Edit { paths })
588        }
589        tools::UNIFIED_FILE => match tool_intent::file_operation_action(args) {
590            Some("read") => Some(PermissionRequestKind::Read { paths }),
591            Some("edit") | Some("patch") => Some(PermissionRequestKind::Edit { paths }),
592            Some(_) => Some(PermissionRequestKind::Write { paths }),
593            None => None,
594        },
595        _ => None,
596    }
597}
598
599fn extract_candidate_paths(
600    workspace_root: &Path,
601    current_dir: &Path,
602    normalized_tool_name: &str,
603    args: &Value,
604) -> Vec<PathBuf> {
605    let mut paths = Vec::new();
606
607    if let Some(obj) = args.as_object() {
608        for key in ["path", "file_path", "filepath", "target_path", "destination"] {
609            if let Some(path) = obj.get(key).and_then(Value::as_str) {
610                push_resolved_path(&mut paths, workspace_root, current_dir, path);
611            }
612        }
613    }
614
615    if normalized_tool_name == tools::APPLY_PATCH {
616        // Decode and parse through the same path the executor uses: a naive
617        // line scan would miss base64 payloads entirely (deny bypass).
618        for patch_path in crate::tools::apply_patch::mutation_target_paths(normalized_tool_name, args) {
619            push_resolved_path(&mut paths, workspace_root, current_dir, &patch_path.to_string_lossy());
620        }
621    }
622
623    paths.sort();
624    paths.dedup();
625    paths
626}
627
628fn push_resolved_path(paths: &mut Vec<PathBuf>, workspace_root: &Path, current_dir: &Path, raw: &str) {
629    let trimmed = raw.trim();
630    if trimmed.is_empty() {
631        return;
632    }
633
634    let resolved = if Path::new(trimmed).is_absolute() {
635        PathBuf::from(trimmed)
636    } else if current_dir.starts_with(workspace_root) {
637        current_dir.join(trimmed)
638    } else {
639        workspace_root.join(trimmed)
640    };
641    paths.push(crate::utils::path::normalize_path(&resolved));
642}
643
644fn extract_web_domains(args: &Value) -> Vec<String> {
645    args.get("url")
646        .and_then(Value::as_str)
647        .and_then(extract_url_domain)
648        .into_iter()
649        .collect::<Vec<_>>()
650}
651
652fn extract_url_domain(url: &str) -> Option<String> {
653    let parsed = Url::parse(url).ok()?;
654    parsed.host_str().map(|host| host.trim_end_matches('.').to_ascii_lowercase())
655}
656
657fn protected_write_paths(workspace_root: &Path, kind: &PermissionRequestKind) -> Vec<PathBuf> {
658    let paths = match kind {
659        PermissionRequestKind::Edit { paths } | PermissionRequestKind::Write { paths } => paths,
660        _ => return Vec::new(),
661    };
662
663    paths
664        .iter()
665        .filter(|path| is_protected_write_path(workspace_root, path))
666        .cloned()
667        .collect()
668}
669
670fn is_protected_write_path(workspace_root: &Path, path: &Path) -> bool {
671    let relative = path.strip_prefix(workspace_root).ok();
672    let Some(relative) = relative else {
673        return false;
674    };
675
676    let as_string = relative.to_string_lossy().replace('\\', "/");
677    if matches!(as_string.as_str(), ".vtcode/commands" | ".vtcode/agents" | ".vtcode/skills")
678        || as_string.starts_with(".vtcode/commands/")
679        || as_string.starts_with(".vtcode/agents/")
680        || as_string.starts_with(".vtcode/skills/")
681    {
682        return false;
683    }
684
685    matches!(as_string.split('/').next(), Some(".git" | ".vtcode" | ".vscode" | ".idea"))
686}
687
688fn domain_matches_allowed(domain: &str, allowed: &str) -> bool {
689    let normalized_domain = domain.trim_end_matches('.').to_ascii_lowercase();
690    let normalized_allowed = allowed.trim_start_matches('.').trim_end_matches('.').to_ascii_lowercase();
691
692    normalized_domain == normalized_allowed || normalized_domain.ends_with(&format!(".{normalized_allowed}"))
693}
694
695#[cfg(test)]
696mod tests;