Skip to main content

vtcode_config/core/
dotfile_protection.rs

1//! Dotfile protection configuration.
2//!
3//! Provides comprehensive protection for hidden configuration files (dotfiles)
4//! to prevent automatic or implicit modifications by AI agents or automated tools.
5
6use crate::env_helpers::default_true;
7use indexmap::IndexSet;
8use serde::{Deserialize, Serialize};
9use vtcode_commons::VtCodePaths;
10
11/// Dotfile protection configuration.
12#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
13#[derive(Debug, Clone, Deserialize, Serialize)]
14pub struct DotfileProtectionConfig {
15    /// Enable dotfile protection globally.
16    #[serde(default = "default_true")]
17    pub enabled: bool,
18
19    /// Require explicit user confirmation for any dotfile modification.
20    #[serde(default = "default_true")]
21    pub require_explicit_confirmation: bool,
22
23    /// Enable immutable audit logging of all dotfile access attempts.
24    #[serde(default = "default_true")]
25    pub audit_logging_enabled: bool,
26
27    /// Path to the audit log file.
28    #[serde(default = "default_audit_log_path")]
29    pub audit_log_path: String,
30
31    /// Prevent cascading modifications (one dotfile change triggering others).
32    #[serde(default = "default_true")]
33    pub prevent_cascading_modifications: bool,
34
35    /// Create backup before any permitted modification.
36    #[serde(default = "default_true")]
37    pub create_backups: bool,
38
39    /// Directory for storing dotfile backups.
40    #[serde(default = "default_backup_dir")]
41    pub backup_directory: String,
42
43    /// Maximum number of backups to retain per file.
44    #[serde(default = "default_max_backups")]
45    pub max_backups_per_file: usize,
46
47    /// Preserve original file permissions and ownership.
48    ///
49    /// NOTE: reserved for future use — restore currently always preserves
50    /// permissions on Unix regardless of this setting.
51    #[serde(default = "default_true")]
52    pub preserve_permissions: bool,
53
54    /// Whitelisted dotfiles that can be modified (after secondary confirmation).
55    #[serde(default)]
56    pub whitelist: IndexSet<String>,
57
58    /// Additional dotfile patterns to protect (beyond defaults).
59    #[serde(default)]
60    pub additional_protected_patterns: Vec<String>,
61
62    /// Block modifications during automated operations.
63    #[serde(default = "default_true")]
64    pub block_during_automation: bool,
65
66    /// Operations that trigger extra protection.
67    ///
68    /// NOTE: reserved for future use — no enforcement reads this list yet.
69    #[serde(default = "default_blocked_operations")]
70    pub blocked_operations: Vec<String>,
71
72    /// Secondary authentication required for whitelisted files.
73    #[serde(default = "default_true")]
74    pub require_secondary_auth_for_whitelist: bool,
75}
76
77impl Default for DotfileProtectionConfig {
78    fn default() -> Self {
79        Self {
80            enabled: default_true(),
81            require_explicit_confirmation: default_true(),
82            audit_logging_enabled: default_true(),
83            audit_log_path: default_audit_log_path(),
84            prevent_cascading_modifications: default_true(),
85            create_backups: default_true(),
86            backup_directory: default_backup_dir(),
87            max_backups_per_file: default_max_backups(),
88            preserve_permissions: default_true(),
89            whitelist: IndexSet::new(),
90            additional_protected_patterns: Vec::new(),
91            block_during_automation: default_true(),
92            blocked_operations: default_blocked_operations(),
93            require_secondary_auth_for_whitelist: default_true(),
94        }
95    }
96}
97
98/// Default protected dotfile patterns.
99///
100/// These patterns match common configuration files that should never be
101/// modified automatically by AI agents or automated tools.
102const DEFAULT_PROTECTED_DOTFILES: &[&str] = &[
103    // Git configuration
104    ".gitignore",
105    ".gitattributes",
106    ".gitmodules",
107    ".gitconfig",
108    ".git-credentials",
109    // Editor configuration
110    ".editorconfig",
111    ".vscode/*",
112    ".idea/*",
113    ".cursor/*",
114    // Environment files
115    ".env",
116    ".env.local",
117    ".env.development",
118    ".env.production",
119    ".env.test",
120    ".env.*",
121    // Docker
122    ".dockerignore",
123    ".docker/*",
124    // Node.js/JavaScript
125    ".npmignore",
126    ".npmrc",
127    ".nvmrc",
128    ".yarnrc",
129    ".yarnrc.yml",
130    ".pnpmrc",
131    // Code formatting
132    ".prettierrc",
133    ".prettierrc.json",
134    ".prettierrc.yml",
135    ".prettierrc.yaml",
136    ".prettierrc.js",
137    ".prettierrc.cjs",
138    ".prettierignore",
139    // Linting
140    ".eslintrc",
141    ".eslintrc.json",
142    ".eslintrc.yml",
143    ".eslintrc.yaml",
144    ".eslintrc.js",
145    ".eslintrc.cjs",
146    ".eslintignore",
147    ".stylelintrc",
148    ".stylelintrc.json",
149    // Build tools
150    ".babelrc",
151    ".babelrc.json",
152    ".babelrc.js",
153    ".swcrc",
154    ".tsbuildinfo",
155    // Shell configuration
156    ".zshrc",
157    ".bashrc",
158    ".bash_profile",
159    ".bash_history",
160    ".bash_logout",
161    ".profile",
162    ".zprofile",
163    ".zshenv",
164    ".zsh_history",
165    ".shrc",
166    ".kshrc",
167    ".cshrc",
168    ".tcshrc",
169    ".fishrc",
170    ".config/fish/*",
171    // Editor configurations
172    ".vimrc",
173    ".vim/*",
174    ".nvim/*",
175    ".config/nvim/*",
176    ".emacs",
177    ".emacs.d/*",
178    ".nanorc",
179    // Terminal multiplexers
180    ".tmux.conf",
181    ".screenrc",
182    // SSH and security
183    ".ssh/*",
184    ".ssh/config",
185    ".ssh/known_hosts",
186    ".ssh/authorized_keys",
187    ".gnupg/*",
188    ".gpg/*",
189    // Cloud credentials
190    ".aws/*",
191    ".aws/config",
192    ".aws/credentials",
193    ".azure/*",
194    ".config/gcloud/*",
195    ".kube/*",
196    ".kube/config",
197    // Package managers and tools
198    ".cargo/*",
199    ".cargo/config.toml",
200    ".cargo/credentials.toml",
201    ".rustup/*",
202    ".gem/*",
203    ".bundle/*",
204    ".pip/*",
205    ".pypirc",
206    ".poetry/*",
207    ".pdm.toml",
208    ".python-version",
209    ".ruby-version",
210    ".node-version",
211    ".go-version",
212    ".tool-versions",
213    // Database
214    ".pgpass",
215    ".my.cnf",
216    ".mongorc.js",
217    ".rediscli_history",
218    // Misc configuration
219    ".netrc",
220    ".curlrc",
221    ".wgetrc",
222    ".htaccess",
223    ".htpasswd",
224    // VT Code specific
225    ".vtcode/*",
226    ".vtcodegitignore",
227    ".vtcode.toml",
228    // Claude/AI
229    ".claude/*",
230    ".claude.json",
231    ".agent/*",
232    // Other common dotfiles
233    ".inputrc",
234    ".dircolors",
235    ".mailrc",
236    ".gitkeep",
237    ".keep",
238];
239
240/// Operations that should never automatically modify dotfiles.
241fn default_blocked_operations() -> Vec<String> {
242    vec![
243        "dependency_installation".into(),
244        "code_formatting".into(),
245        "git_operations".into(),
246        "project_initialization".into(),
247        "build_operations".into(),
248        "test_execution".into(),
249        "linting".into(),
250        "auto_fix".into(),
251    ]
252}
253
254#[inline]
255fn default_audit_log_path() -> String {
256    VtCodePaths::resolve()
257        .and_then(|paths| paths.state_path("audit/dotfiles.log"))
258        .map(|path| path.display().to_string())
259        .unwrap_or_else(|_| String::from("state/vtcode/audit/dotfiles.log"))
260}
261
262#[inline]
263fn default_backup_dir() -> String {
264    VtCodePaths::resolve()
265        .and_then(|paths| paths.state_path("backups/dotfiles"))
266        .map(|path| path.display().to_string())
267        .unwrap_or_else(|_| String::from("state/vtcode/backups/dotfiles"))
268}
269
270#[inline]
271const fn default_max_backups() -> usize {
272    10
273}
274
275impl DotfileProtectionConfig {
276    /// Check if a file path matches a protected dotfile pattern.
277    pub fn is_protected(&self, path: &str) -> bool {
278        if !self.enabled {
279            return false;
280        }
281
282        // Normalize Windows separators first: nested-dotdir detection splits
283        // on `/`, so without this `C:\u\.ssh\config` would evade every check.
284        // On Unix a literal backslash can only widen matches (fail-closed).
285        let normalized = path.replace('\\', "/");
286        let path = normalized.as_str();
287        let filename = std::path::Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or(path);
288
289        // Check if it's a dotfile (starts with . or contains /. or is in a dotfile directory)
290        let is_dotfile = filename.starts_with('.')
291            || path.contains("/.")
292            || path.starts_with('.')
293            || Self::is_in_dotfile_directory(path);
294
295        if !is_dotfile {
296            return false;
297        }
298
299        // Check against default patterns
300        for pattern in DEFAULT_PROTECTED_DOTFILES {
301            if Self::matches_pattern(path, pattern) || Self::matches_pattern(filename, pattern) {
302                return true;
303            }
304        }
305
306        // Check against additional patterns
307        for pattern in &self.additional_protected_patterns {
308            if Self::matches_pattern(path, pattern) || Self::matches_pattern(filename, pattern) {
309                return true;
310            }
311        }
312
313        // Default: protect any file starting with .
314        filename.starts_with('.') || Self::is_in_dotfile_directory(path)
315    }
316
317    /// Check if a path is inside a dotfile directory like .ssh, .aws, etc.
318    fn is_in_dotfile_directory(path: &str) -> bool {
319        let components: Vec<&str> = path.split('/').collect();
320        for component in &components {
321            if component.starts_with('.') && !component.is_empty() && *component != "." && *component != ".." {
322                return true;
323            }
324        }
325        false
326    }
327
328    /// Check if a file is in the whitelist.
329    ///
330    /// Compares separator-normalized forms on both sides, so a whitelist
331    /// entry written with `\` still matches the same path written with `/`
332    /// (whitelisted files face the stronger secondary-auth gate, so a missed
333    /// match would weaken protection).
334    pub fn is_whitelisted(&self, path: &str) -> bool {
335        let normalized = path.replace('\\', "/");
336        let filename = std::path::Path::new(&normalized)
337            .file_name()
338            .and_then(|n| n.to_str())
339            .unwrap_or(&normalized);
340        self.whitelist.iter().any(|entry| {
341            let entry_normalized = entry.replace('\\', "/");
342            let entry_filename = std::path::Path::new(&entry_normalized)
343                .file_name()
344                .and_then(|n| n.to_str())
345                .unwrap_or(&entry_normalized);
346            entry_normalized == normalized || entry_filename == filename
347        })
348    }
349
350    /// Simple pattern matching with wildcard support.
351    fn matches_pattern(path: &str, pattern: &str) -> bool {
352        if pattern.contains('*') {
353            // Handle wildcard patterns
354            if let Some(prefix) = pattern.strip_suffix("/*") {
355                path.starts_with(prefix) || path.contains(&format!("/{}/", prefix.trim_start_matches('.')))
356            } else if pattern.ends_with(".*") {
357                let prefix = &pattern[..pattern.len() - 1];
358                path.starts_with(prefix)
359            } else {
360                // Simple glob matching
361                let parts: Vec<&str> = pattern.split('*').collect();
362                if parts.len() == 2 {
363                    path.starts_with(parts[0]) && path.ends_with(parts[1])
364                } else {
365                    path == pattern
366                }
367            }
368        } else {
369            path == pattern || path.ends_with(&format!("/{pattern}"))
370        }
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377
378    #[test]
379    fn test_default_protection() {
380        let config = DotfileProtectionConfig::default();
381
382        // Should be protected
383        assert!(config.is_protected(".gitignore"));
384        assert!(config.is_protected(".env"));
385        assert!(config.is_protected(".env.local"));
386        assert!(config.is_protected(".bashrc"));
387        assert!(config.is_protected(".ssh/config"));
388        assert!(config.is_protected("/home/user/.npmrc"));
389
390        // Should not be protected (not dotfiles)
391        assert!(!config.is_protected("README.md"));
392        assert!(!config.is_protected("src/main.rs"));
393    }
394
395    #[test]
396    fn test_whitelist() {
397        let mut config = DotfileProtectionConfig::default();
398        config.whitelist.insert(".gitignore".into());
399
400        assert!(config.is_whitelisted(".gitignore"));
401        assert!(!config.is_whitelisted(".env"));
402    }
403
404    #[test]
405    fn test_disabled_protection() {
406        let config = DotfileProtectionConfig { enabled: false, ..Default::default() };
407
408        assert!(!config.is_protected(".gitignore"));
409        assert!(!config.is_protected(".env"));
410    }
411
412    #[test]
413    fn test_pattern_matching() {
414        assert!(DotfileProtectionConfig::matches_pattern(".env.local", ".env.*"));
415        assert!(DotfileProtectionConfig::matches_pattern(".env.production", ".env.*"));
416        assert!(DotfileProtectionConfig::matches_pattern(".vscode/settings.json", ".vscode/*"));
417    }
418
419    #[test]
420    fn test_windows_separators_do_not_evade_detection() {
421        let config = DotfileProtectionConfig::default();
422
423        assert!(config.is_protected("C:\\Users\\test\\.ssh\\config"));
424        assert!(config.is_protected(".ssh\\known_hosts"));
425        assert!(config.is_protected("C:\\Users\\test\\.env"));
426        assert!(!config.is_protected("C:\\Users\\test\\README.md"));
427        assert!(!config.is_protected("C:\\Users\\test\\src\\main.rs"));
428    }
429
430    #[test]
431    fn test_whitelist_matches_across_separator_styles() {
432        let mut config = DotfileProtectionConfig::default();
433        config.whitelist.insert("C:\\Users\\test\\.gitignore".into());
434
435        assert!(config.is_whitelisted("C:\\Users\\test\\.gitignore"));
436        assert!(config.is_whitelisted("C:/Users/test/.gitignore"));
437    }
438}