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 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;