vtcode-core 0.170.0

Core library for VT Code - a Rust-based terminal coding agent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use crate::audit::PermissionDecision;
use crate::config::CommandsConfig;
use crate::tools::command_cache::PermissionCache;
use crate::tools::command_resolver::CommandResolver;
use regex::Regex;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use tracing::warn;

#[derive(Clone)]
pub struct CommandPolicyEvaluator {
    allow_prefixes: Vec<String>,
    deny_prefixes: Vec<String>,
    allow_regexes: Vec<Regex>,
    deny_regexes: Vec<Regex>,
    allow_glob_regexes: Vec<Regex>,
    deny_glob_regexes: Vec<Regex>,
    allow_regexes_empty: bool,
    allow_globs_empty: bool,
    // NEW: Command resolution and caching for improved security visibility
    resolver: Arc<Mutex<CommandResolver>>,
    cache: Arc<Mutex<PermissionCache>>,
}

impl CommandPolicyEvaluator {
    pub fn from_config(config: &CommandsConfig) -> Self {
        let allow_prefixes = crate::utils::merge_env_patterns(&config.allow_list, "VTCODE_COMMANDS_ALLOW_LIST");
        // Deny prefix entries are matched against policy segments whose
        // leading `KEY=value` / `env` words are already stripped, so an entry
        // authored with an assignment prefix (`FOO=1 rm`) would never match.
        // Normalize the entry the same way; this is fail-safe because it can
        // only widen deny matching, never narrow it.
        let deny_prefixes = crate::utils::merge_env_patterns(&config.deny_list, "VTCODE_COMMANDS_DENY_LIST")
            .into_iter()
            .map(|pattern| {
                let words: Vec<String> = pattern.split_whitespace().map(str::to_string).collect();
                crate::tools::command_args::command_words_after_environment_prefix(&words).join(" ")
            })
            .collect::<Vec<_>>();

        let allow_regex_patterns = crate::utils::merge_env_patterns(&config.allow_regex, "VTCODE_COMMANDS_ALLOW_REGEX");
        let deny_regex_patterns = crate::utils::merge_env_patterns(&config.deny_regex, "VTCODE_COMMANDS_DENY_REGEX");

        let allow_glob_patterns = crate::utils::merge_env_patterns(&config.allow_glob, "VTCODE_COMMANDS_ALLOW_GLOB");
        let deny_glob_patterns = crate::utils::merge_env_patterns(&config.deny_glob, "VTCODE_COMMANDS_DENY_GLOB");

        let allow_regexes = compile_regexes(&allow_regex_patterns);
        let deny_regexes = compile_regexes(&deny_regex_patterns);
        let allow_glob_regexes = compile_globs(&allow_glob_patterns);
        let deny_glob_regexes = compile_globs(&deny_glob_patterns);

        Self {
            allow_prefixes,
            deny_prefixes,
            allow_regexes,
            deny_regexes,
            allow_glob_regexes,
            deny_glob_regexes,
            allow_regexes_empty: allow_regex_patterns.is_empty(),
            allow_globs_empty: allow_glob_patterns.is_empty(),
            resolver: Arc::new(Mutex::new(CommandResolver::new())),
            cache: Arc::new(Mutex::new(PermissionCache::new())),
        }
    }

    fn cached_decision(&self, command_text: &str) -> Option<bool> {
        self.cache
            .lock()
            .unwrap_or_else(|poisoned| {
                warn!("command_policy: permission cache mutex poisoned; recovering");
                poisoned.into_inner()
            })
            .get(command_text)
    }

    fn resolve_path(&self, command_text: &str) -> Option<PathBuf> {
        self.resolver
            .lock()
            .unwrap_or_else(|poisoned| {
                warn!("command_policy: command resolver mutex poisoned; recovering");
                poisoned.into_inner()
            })
            .resolve(command_text)
            .resolved_path
            .clone()
    }

    fn cache_decision(&self, command_text: &str, allowed: bool, reason: &str) {
        let mut cache = self.cache.lock().unwrap_or_else(|poisoned| {
            warn!("command_policy: permission cache mutex poisoned; recovering");
            poisoned.into_inner()
        });
        cache.put(command_text, allowed, reason);
    }

    pub fn allows(&self, command: &[String]) -> bool {
        if command.is_empty() {
            return false;
        }
        // Preserve argv boundaries when checking a direct executable. Joining
        // raw arguments would let punctuation inside an argument (for example
        // Python's `;` or a quoted string) look like shell operators. Explicit
        // shell wrappers are handled separately so their script still receives
        // segment-level validation.
        let command_text =
            shell_script_from_argv(command).unwrap_or_else(|| shell_words::join(command.iter().map(String::as_str)));
        self.allows_text(&command_text)
    }

    pub fn allows_text(&self, command_text: &str) -> bool {
        let cmd = command_text.trim();
        if cmd.is_empty() {
            return false;
        }

        let segments = policy_segments(cmd);

        // Deny takes precedence. Every shell segment is evaluated so chained,
        // piped, or list-joined commands cannot ride on an earlier match.
        if segments.iter().any(|segment| {
            self.matches_prefix(segment, &self.deny_prefixes)
                || Self::matches_any(&self.deny_regexes, segment)
                || Self::matches_any(&self.deny_glob_regexes, segment)
        }) {
            return false;
        }

        // If no allow rules defined, allow by default
        if self.allow_prefixes.is_empty() && self.allow_regexes_empty && self.allow_globs_empty {
            return true;
        }

        // Check allow rules: each segment must independently match
        segments.iter().all(|segment| {
            self.matches_prefix(segment, &self.allow_prefixes)
                || Self::matches_any(&self.allow_regexes, segment)
                || Self::matches_any(&self.allow_glob_regexes, segment)
        })
    }

    /// Enhanced async evaluation with command resolution and caching
    /// Returns (allowed, resolved_path, reason, decision)
    pub fn evaluate_with_resolution(&self, command_text: &str) -> (bool, Option<PathBuf>, String, PermissionDecision) {
        let cmd = command_text.trim();

        // Check cache first
        if let Some(allowed) = self.cached_decision(cmd) {
            let reason = if allowed {
                "Cached allow decision"
            } else {
                "Cached deny decision"
            };
            return (allowed, None, reason.to_string(), PermissionDecision::Cached);
        }

        // Resolve command to actual path
        let resolved_path = self.resolve_path(cmd);

        // Evaluate policy
        let allowed = self.allows_text(cmd);

        // Determine reason - use static strings where possible to avoid allocations
        let reason = if allowed {
            if self.matches_prefix(cmd, &self.allow_prefixes) {
                format!("allow_list match: {cmd}")
            } else if Self::matches_any(&self.allow_glob_regexes, cmd) {
                "allow_glob match".to_string()
            } else {
                "allow_regex match".to_string()
            }
        } else if self.matches_prefix(cmd, &self.deny_prefixes) {
            format!("deny_list match: {cmd}")
        } else if Self::matches_any(&self.deny_glob_regexes, cmd) {
            "deny_glob match".to_string()
        } else {
            "deny_regex match".to_string()
        };

        // Cache the result
        self.cache_decision(cmd, allowed, &reason);

        let decision = if allowed {
            PermissionDecision::Allowed
        } else {
            PermissionDecision::Denied
        };

        (allowed, resolved_path, reason, decision)
    }

    fn matches_prefix(&self, value: &str, prefixes: &[String]) -> bool {
        prefixes
            .iter()
            .filter(|pattern| !pattern.is_empty())
            .any(|pattern| value.starts_with(pattern))
    }
    fn matches_any(regexes: &[Regex], value: &str) -> bool {
        regexes.iter().any(|re| re.is_match(value))
    }
}

/// Return the script carried by an explicit shell invocation.
///
/// The exec tool accepts both a regular argv request (`["printf", "ok"]`) and
/// an already-constructed shell request (`["/bin/sh", "-lc", "printf ok"]`).
/// Command policy must inspect the script in the latter form; matching the
/// wrapper itself would reject safe commands and could also hide a denied
/// command behind the shell name.
fn shell_script_from_argv(command: &[String]) -> Option<String> {
    let program = command.first()?;
    let basename = Path::new(program).file_name()?.to_str()?.to_ascii_lowercase();
    let shell_kind = match basename.as_str() {
        "sh" | "bash" | "zsh" | "dash" | "ksh" => ShellInvocationKind::Posix,
        "cmd" | "cmd.exe" => ShellInvocationKind::Cmd,
        "powershell" | "powershell.exe" | "pwsh" | "pwsh.exe" => ShellInvocationKind::PowerShell,
        _ => return None,
    };

    let flag_index = command.iter().enumerate().skip(1).find_map(|(index, argument)| {
        let is_command_flag = match shell_kind {
            ShellInvocationKind::Posix => {
                argument == "-c"
                    || (argument.starts_with('-')
                        && !argument.starts_with("--")
                        && argument.as_bytes().get(1..).is_some_and(|flags| flags.contains(&b'c')))
            }
            ShellInvocationKind::Cmd => argument.eq_ignore_ascii_case("/c") || argument.eq_ignore_ascii_case("/k"),
            ShellInvocationKind::PowerShell => {
                matches!(argument.to_ascii_lowercase().as_str(), "-command" | "-c" | "-encodedcommand" | "-e")
            }
        };
        is_command_flag.then_some(index)
    })?;

    command.get(flag_index + 1).cloned()
}

/// Return whether argv explicitly names a supported shell, even when it does
/// not carry a `-c` script. Callers use this to preserve the user's shell
/// boundary while selecting the policy representation.
pub(crate) fn is_shell_argv(command: &[String]) -> bool {
    command
        .first()
        .and_then(|program| Path::new(program).file_name())
        .and_then(|name| name.to_str())
        .is_some_and(|name| {
            matches!(
                name.to_ascii_lowercase().as_str(),
                "sh" | "bash"
                    | "zsh"
                    | "dash"
                    | "ksh"
                    | "cmd"
                    | "cmd.exe"
                    | "powershell"
                    | "powershell.exe"
                    | "pwsh"
                    | "pwsh.exe"
            )
        })
}

#[derive(Clone, Copy)]
enum ShellInvocationKind {
    Posix,
    Cmd,
    PowerShell,
}

/// Split a command string into its shell segments so prefix/regex policy
/// rules apply to every chained, piped, or list-joined command rather than
/// only to the first. Falls back to the whole string when the parser cannot
/// handle the syntax, preserving the previous whole-string behavior.
fn policy_segments(command_text: &str) -> Vec<String> {
    match crate::command_safety::shell_parser::parse_shell_commands(command_text) {
        Ok(segments) if !segments.is_empty() => segments
            .into_iter()
            .map(|argv| {
                // The shell parser keeps leading `KEY=value` assignments as
                // words so intent/activity classification can inspect injection
                // keys. For policy matching they are the command's environment,
                // not its executable: strip them so `FOO=bar rg …` still matches
                // the allow rule for `rg` (shared helper, single source of truth).
                crate::tools::command_args::command_words_after_environment_prefix(&argv).join(" ")
            })
            .collect(),
        _ => vec![command_text.to_string()],
    }
}

fn compile_regexes(patterns: &[String]) -> Vec<Regex> {
    patterns
        .iter()
        .filter_map(|pattern| {
            Regex::new(pattern)
                .map_err(|error| {
                    warn!(%error, %pattern, "Ignoring invalid command regex pattern");
                    error
                })
                .ok()
        })
        .collect()
}

fn compile_globs(patterns: &[String]) -> Vec<Regex> {
    patterns
        .iter()
        .filter_map(|pattern| {
            let escaped = regex::escape(pattern);
            let glob_regex = format!("^{}$", escaped.replace(r"\*", ".*").replace(r"\?", "."));
            Regex::new(&glob_regex)
                .map_err(|error| {
                    warn!(%error, pattern = %pattern, "Ignoring invalid command glob pattern");
                    error
                })
                .ok()
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::CommandsConfig;

    #[test]
    fn glob_allows_cargo_commands() {
        let mut config = CommandsConfig::default();
        config.allow_list.clear();
        config.allow_regex.clear();
        config.allow_glob = vec!["cargo *".to_string()];
        let evaluator = CommandPolicyEvaluator::from_config(&config);
        assert!(evaluator.allows_text("cargo fmt"));
        assert!(evaluator.allows(&["cargo".into(), "check".into()]));
    }

    /// Environment-assignment prefixes are the command's environment, not its
    /// executable: `FOO=bar rg …` / `IFS= read …` must still match the allow
    /// rule for the real program. Regression guard for the shell parser keeping
    /// `KEY=value` words so intent/activity classification can inspect them.
    #[test]
    fn environment_prefix_does_not_block_allow_rules() {
        let prefix = CommandsConfig {
            allow_list: vec!["rg".into(), "read".into(), "printf".into()],
            ..Default::default()
        };
        let prefixed = CommandPolicyEvaluator::from_config(&prefix);
        assert!(prefixed.allows(&["LANG=C".into(), "rg".into(), "foo".into()]));
        assert!(prefixed.allows(&["IFS=".into(), "read".into(), "-r".into(), "line".into()]));
        // An explicit shell wrapper carries the prefix inside its script.
        assert!(prefixed.allows_text("LANG=C rg foo"));

        // A denied program stays denied even behind an assignment prefix.
        let deny = CommandsConfig {
            allow_list: vec!["rg".into()],
            deny_list: vec!["rm".into()],
            ..Default::default()
        };
        let denying = CommandPolicyEvaluator::from_config(&deny);
        assert!(denying.allows(&["LANG=C".into(), "rg".into()]));
        assert!(!denying.allows(&["FOO=1".into(), "rm".into(), "-rf".into(), "/".into()]));
    }

    /// A deny entry authored *with* an assignment prefix (`FOO=1 rm`) must
    /// still match: deny entries are compared against segments whose leading
    /// `KEY=value` words are stripped, so the entry is normalized the same way
    /// at construction. Fail-safe direction: this can only widen deny
    /// matching, never narrow it.
    #[test]
    fn deny_entry_with_env_prefix_matches_stripped_segment() {
        let config = CommandsConfig {
            allow_list: vec!["rg".into()],
            deny_list: vec!["FOO=1 rm".into(), "env rm".into()],
            ..Default::default()
        };
        let evaluator = CommandPolicyEvaluator::from_config(&config);
        // Both prefix forms of the deny entry collapse onto the bare program.
        assert!(!evaluator.allows(&["FOO=1".into(), "rm".into(), "-rf".into(), "/".into()]));
        assert!(!evaluator.allows(&["env".into(), "rm".into(), "x".into()]));
        assert!(!evaluator.allows_text("FOO=1 rm -rf /"));
        // The allow rule for `rg` is unaffected by deny-entry normalization.
        assert!(evaluator.allows(&["rg".into(), "foo".into()]));
        assert!(evaluator.allows(&["LANG=C".into(), "rg".into(), "foo".into()]));
    }

    #[test]
    fn glob_supports_question_mark() {
        let mut config = CommandsConfig::default();
        config.allow_list.clear();
        config.allow_regex.clear();
        config.allow_glob = vec!["go test ./pkg/?".to_string()];
        let evaluator = CommandPolicyEvaluator::from_config(&config);
        assert!(evaluator.allows_text("go test ./pkg/a"));
        assert!(!evaluator.allows_text("go test ./pkg/ab"));
    }

    #[test]
    fn glob_allows_node_ecosystem_commands() {
        let mut config = CommandsConfig::default();
        config.allow_list.clear();
        config.allow_regex.clear();
        config.allow_glob = vec!["npm *".to_string(), "bun *".to_string()];
        let evaluator = CommandPolicyEvaluator::from_config(&config);
        assert!(evaluator.allows_text("npm install"));
        assert!(evaluator.allows_text("npm run build"));
        assert!(evaluator.allows_text("bun install"));
        assert!(evaluator.allows_text("bun run check"));
    }

    #[test]
    fn allow_list_allows_exact_git_and_cargo_commands() {
        let mut config = CommandsConfig::default();
        // Clear default allow_list to reduce noise
        config.allow_list.clear();
        config.allow_list.push("git".to_string());
        config.allow_list.push("cargo".to_string());
        let evaluator = CommandPolicyEvaluator::from_config(&config);
        assert!(evaluator.allows_text("git"));
        assert!(evaluator.allows_text("cargo"));
        assert!(evaluator.allows(&["git".into()]));
        assert!(evaluator.allows(&["cargo".into()]));
    }

    #[test]
    fn shell_wrapper_policy_evaluates_inner_script() {
        let evaluator = CommandPolicyEvaluator::from_config(&CommandsConfig::default());
        assert!(evaluator.allows(&["/bin/sh".into(), "-lc".into(), "printf vtcode-terminal".into(),]));
        assert!(!evaluator.allows(&["/bin/sh".into(), "-lc".into(), "rm -rf /".into(),]));
    }
}