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    ".bunfig.toml",
132    // Code formatting
133    ".prettierrc",
134    ".prettierrc.json",
135    ".prettierrc.yml",
136    ".prettierrc.yaml",
137    ".prettierrc.js",
138    ".prettierrc.cjs",
139    ".prettierignore",
140    // Linting
141    ".eslintrc",
142    ".eslintrc.json",
143    ".eslintrc.yml",
144    ".eslintrc.yaml",
145    ".eslintrc.js",
146    ".eslintrc.cjs",
147    ".eslintignore",
148    ".stylelintrc",
149    ".stylelintrc.json",
150    // Build tools
151    ".babelrc",
152    ".babelrc.json",
153    ".babelrc.js",
154    ".swcrc",
155    ".tsbuildinfo",
156    // Shell configuration
157    ".zshrc",
158    ".bashrc",
159    ".bash_profile",
160    ".bash_history",
161    ".bash_logout",
162    ".profile",
163    ".zprofile",
164    ".zshenv",
165    ".zsh_history",
166    ".shrc",
167    ".kshrc",
168    ".cshrc",
169    ".tcshrc",
170    ".fishrc",
171    ".config/fish/*",
172    // Editor configurations
173    ".vimrc",
174    ".vim/*",
175    ".nvim/*",
176    ".config/nvim/*",
177    ".emacs",
178    ".emacs.d/*",
179    ".nanorc",
180    // Terminal multiplexers
181    ".tmux.conf",
182    ".screenrc",
183    // SSH and security
184    ".ssh/*",
185    ".ssh/config",
186    ".ssh/known_hosts",
187    ".ssh/authorized_keys",
188    ".gnupg/*",
189    ".gpg/*",
190    // Cloud credentials
191    ".aws/*",
192    ".aws/config",
193    ".aws/credentials",
194    ".azure/*",
195    ".config/gcloud/*",
196    ".kube/*",
197    ".kube/config",
198    // Package managers and tools
199    ".cargo/*",
200    ".cargo/config.toml",
201    ".cargo/credentials.toml",
202    ".rustup/*",
203    ".gem/*",
204    ".bundle/*",
205    ".pip/*",
206    ".pypirc",
207    ".poetry/*",
208    ".pdm.toml",
209    ".python-version",
210    ".ruby-version",
211    ".node-version",
212    ".go-version",
213    ".tool-versions",
214    // Database
215    ".pgpass",
216    ".my.cnf",
217    ".mongorc.js",
218    ".rediscli_history",
219    // Misc configuration
220    ".netrc",
221    ".curlrc",
222    ".wgetrc",
223    ".htaccess",
224    ".htpasswd",
225    // VT Code specific
226    ".vtcode/*",
227    ".vtcodegitignore",
228    ".vtcode.toml",
229    // Claude/AI
230    ".claude/*",
231    ".claude.json",
232    ".agent/*",
233    // Other common dotfiles
234    ".inputrc",
235    ".dircolors",
236    ".mailrc",
237    ".gitkeep",
238    ".keep",
239];
240
241/// Operations that should never automatically modify dotfiles.
242fn default_blocked_operations() -> Vec<String> {
243    vec![
244        "dependency_installation".into(),
245        "code_formatting".into(),
246        "git_operations".into(),
247        "project_initialization".into(),
248        "build_operations".into(),
249        "test_execution".into(),
250        "linting".into(),
251        "auto_fix".into(),
252    ]
253}
254
255#[inline]
256fn default_audit_log_path() -> String {
257    VtCodePaths::resolve()
258        .and_then(|paths| paths.state_path("audit/dotfiles.log"))
259        .map(|path| path.display().to_string())
260        .unwrap_or_else(|_| String::from("state/vtcode/audit/dotfiles.log"))
261}
262
263#[inline]
264fn default_backup_dir() -> String {
265    VtCodePaths::resolve()
266        .and_then(|paths| paths.state_path("backups/dotfiles"))
267        .map(|path| path.display().to_string())
268        .unwrap_or_else(|_| String::from("state/vtcode/backups/dotfiles"))
269}
270
271#[inline]
272const fn default_max_backups() -> usize {
273    10
274}
275
276impl DotfileProtectionConfig {
277    /// Check if a file path matches a protected dotfile pattern.
278    pub fn is_protected(&self, path: &str) -> bool {
279        if !self.enabled {
280            return false;
281        }
282
283        // Normalize Windows separators first: nested-dotdir detection splits
284        // on `/`, so without this `C:\u\.ssh\config` would evade every check.
285        // On Unix a literal backslash can only widen matches (fail-closed).
286        let normalized = path.replace('\\', "/");
287        let path = normalized.as_str();
288        let filename = std::path::Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or(path);
289
290        // Check if it's a dotfile (starts with . or contains /. or is in a dotfile directory)
291        let is_dotfile = filename.starts_with('.')
292            || path.contains("/.")
293            || path.starts_with('.')
294            || Self::is_in_dotfile_directory(path);
295
296        if !is_dotfile {
297            return false;
298        }
299
300        // Check against default patterns
301        for pattern in DEFAULT_PROTECTED_DOTFILES {
302            if Self::matches_pattern(path, pattern) || Self::matches_pattern(filename, pattern) {
303                return true;
304            }
305        }
306
307        // Check against additional patterns
308        for pattern in &self.additional_protected_patterns {
309            if Self::matches_pattern(path, pattern) || Self::matches_pattern(filename, pattern) {
310                return true;
311            }
312        }
313
314        // Default: protect any file starting with .
315        filename.starts_with('.') || Self::is_in_dotfile_directory(path)
316    }
317
318    /// Check if a path is inside a dotfile directory like .ssh, .aws, etc.
319    fn is_in_dotfile_directory(path: &str) -> bool {
320        let components: Vec<&str> = path.split('/').collect();
321        for component in &components {
322            if component.starts_with('.') && !component.is_empty() && *component != "." && *component != ".." {
323                return true;
324            }
325        }
326        false
327    }
328
329    /// Check if a file is in the whitelist.
330    ///
331    /// Compares separator-normalized forms on both sides, so a whitelist
332    /// entry written with `\` still matches the same path written with `/`
333    /// (whitelisted files face the stronger secondary-auth gate, so a missed
334    /// match would weaken protection).
335    pub fn is_whitelisted(&self, path: &str) -> bool {
336        let normalized = path.replace('\\', "/");
337        let filename = std::path::Path::new(&normalized)
338            .file_name()
339            .and_then(|n| n.to_str())
340            .unwrap_or(&normalized);
341        self.whitelist.iter().any(|entry| {
342            let entry_normalized = entry.replace('\\', "/");
343            let entry_filename = std::path::Path::new(&entry_normalized)
344                .file_name()
345                .and_then(|n| n.to_str())
346                .unwrap_or(&entry_normalized);
347            entry_normalized == normalized || entry_filename == filename
348        })
349    }
350
351    /// Simple pattern matching with wildcard support.
352    fn matches_pattern(path: &str, pattern: &str) -> bool {
353        if pattern.contains('*') {
354            // Handle wildcard patterns
355            if let Some(prefix) = pattern.strip_suffix("/*") {
356                path.starts_with(prefix) || path.contains(&format!("/{}/", prefix.trim_start_matches('.')))
357            } else if pattern.ends_with(".*") {
358                let prefix = &pattern[..pattern.len() - 1];
359                path.starts_with(prefix)
360            } else {
361                // Simple glob matching
362                let parts: Vec<&str> = pattern.split('*').collect();
363                if parts.len() == 2 {
364                    path.starts_with(parts[0]) && path.ends_with(parts[1])
365                } else {
366                    path == pattern
367                }
368            }
369        } else {
370            path == pattern || path.ends_with(&format!("/{pattern}"))
371        }
372    }
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    #[test]
380    fn test_default_protection() {
381        let config = DotfileProtectionConfig::default();
382
383        // Should be protected
384        assert!(config.is_protected(".gitignore"));
385        assert!(config.is_protected(".env"));
386        assert!(config.is_protected(".env.local"));
387        assert!(config.is_protected(".bashrc"));
388        assert!(config.is_protected(".ssh/config"));
389        assert!(config.is_protected("/home/user/.npmrc"));
390        assert!(config.is_protected("/home/user/.bunfig.toml"));
391
392        // Should not be protected (not dotfiles)
393        assert!(!config.is_protected("README.md"));
394        assert!(!config.is_protected("src/main.rs"));
395    }
396
397    #[test]
398    fn test_whitelist() {
399        let mut config = DotfileProtectionConfig::default();
400        config.whitelist.insert(".gitignore".into());
401
402        assert!(config.is_whitelisted(".gitignore"));
403        assert!(!config.is_whitelisted(".env"));
404    }
405
406    #[test]
407    fn test_disabled_protection() {
408        let config = DotfileProtectionConfig { enabled: false, ..Default::default() };
409
410        assert!(!config.is_protected(".gitignore"));
411        assert!(!config.is_protected(".env"));
412    }
413
414    #[test]
415    fn test_pattern_matching() {
416        assert!(DotfileProtectionConfig::matches_pattern(".env.local", ".env.*"));
417        assert!(DotfileProtectionConfig::matches_pattern(".env.production", ".env.*"));
418        assert!(DotfileProtectionConfig::matches_pattern(".vscode/settings.json", ".vscode/*"));
419    }
420
421    #[test]
422    fn test_windows_separators_do_not_evade_detection() {
423        let config = DotfileProtectionConfig::default();
424
425        assert!(config.is_protected("C:\\Users\\test\\.ssh\\config"));
426        assert!(config.is_protected(".ssh\\known_hosts"));
427        assert!(config.is_protected("C:\\Users\\test\\.env"));
428        assert!(!config.is_protected("C:\\Users\\test\\README.md"));
429        assert!(!config.is_protected("C:\\Users\\test\\src\\main.rs"));
430    }
431
432    #[test]
433    fn test_whitelist_matches_across_separator_styles() {
434        let mut config = DotfileProtectionConfig::default();
435        config.whitelist.insert("C:\\Users\\test\\.gitignore".into());
436
437        assert!(config.is_whitelisted("C:\\Users\\test\\.gitignore"));
438        assert!(config.is_whitelisted("C:/Users/test/.gitignore"));
439    }
440}