vtcode_core/dotfile_protection/
backup.rs1#[cfg(unix)]
7use std::fs::Permissions;
8#[cfg(unix)]
9use std::os::unix::fs::PermissionsExt;
10use std::path::{Path, PathBuf};
11
12use anyhow::{Context, Result, bail};
13use chrono::{DateTime, Utc};
14use serde::{Deserialize, Serialize};
15use vtcode_commons::VtCodePaths;
16use vtcode_commons::fs::{
17 read_private_file_no_follow, read_private_json_file, write_private_file_atomic, write_private_json_file,
18};
19use vtcode_commons::utils::calculate_sha256;
20
21#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct DotfileBackup {
24 pub original_path: String,
26 pub backup_path: String,
28 pub created_at: DateTime<Utc>,
30 pub content_hash: String,
32 pub size_bytes: u64,
34 #[cfg(unix)]
36 pub permissions: u32,
37 pub reason: String,
39 pub session_id: String,
41}
42
43impl DotfileBackup {
44 pub async fn restore(&self) -> Result<()> {
46 let backup_path = Path::new(&self.backup_path);
47 let original_path = Path::new(&self.original_path);
48
49 if !tokio::fs::symlink_metadata(backup_path)
50 .await
51 .is_ok_and(|metadata| metadata.is_file())
52 {
53 bail!("Backup file does not exist: {}", self.backup_path);
54 }
55
56 let content = read_private_file_no_follow(backup_path)
58 .await
59 .with_context(|| format!("Failed to read backup: {}", self.backup_path))?;
60
61 let hash = calculate_sha256(&content);
62 if hash != self.content_hash {
63 bail!("Backup integrity check failed: hash mismatch for {}", self.backup_path);
64 }
65
66 write_private_file_atomic(original_path, &content)
68 .await
69 .with_context(|| format!("Failed to restore to: {}", self.original_path))?;
70
71 #[cfg(unix)]
73 {
74 let perms = Permissions::from_mode(self.permissions);
75 tokio::fs::set_permissions(original_path, perms)
76 .await
77 .with_context(|| format!("Failed to restore permissions for: {}", self.original_path))?;
78 }
79
80 tracing::info!("Restored dotfile {} from backup {}", self.original_path, self.backup_path);
81
82 Ok(())
83 }
84}
85
86pub struct BackupManager {
88 backup_dir: PathBuf,
90 max_backups: usize,
92}
93
94impl BackupManager {
95 pub async fn new(backup_dir: impl AsRef<Path>, max_backups: usize) -> Result<Self> {
97 let backup_dir = backup_dir.as_ref().to_path_buf();
98
99 VtCodePaths::ensure_user_dir(&backup_dir)
101 .with_context(|| format!("Failed to create backup directory: {backup_dir:?}"))?;
102
103 Ok(Self { backup_dir, max_backups })
104 }
105
106 pub async fn create_backup(
108 &self,
109 file_path: &Path,
110 reason: impl Into<String>,
111 session_id: impl Into<String>,
112 ) -> Result<DotfileBackup> {
113 let content = read_private_file_no_follow(file_path)
115 .await
116 .with_context(|| format!("Failed to read file for backup: {file_path:?}"))?;
117
118 let metadata = tokio::fs::symlink_metadata(file_path)
120 .await
121 .with_context(|| format!("Failed to get metadata: {file_path:?}"))?;
122 if !metadata.is_file() {
123 bail!("Cannot backup non-regular file: {file_path:?}");
124 }
125
126 let content_hash = calculate_sha256(&content);
128
129 let timestamp = Utc::now();
132 let safe_name = self.safe_filename(file_path);
133 let backup_stem = format!("{}.{}.backup", safe_name, timestamp.format("%Y%m%d_%H%M%S_%3f"));
134 let backup_path = self.unique_backup_path(&backup_stem).await;
135
136 write_private_file_atomic(&backup_path, &content)
138 .await
139 .with_context(|| format!("Failed to write backup: {backup_path:?}"))?;
140
141 #[cfg(unix)]
142 let permissions = metadata.permissions().mode();
143
144 let backup = DotfileBackup {
145 original_path: file_path.to_string_lossy().into_owned(),
146 backup_path: backup_path.to_string_lossy().into_owned(),
147 created_at: timestamp,
148 content_hash,
149 size_bytes: metadata.len(),
150 #[cfg(unix)]
151 permissions,
152 reason: reason.into(),
153 session_id: session_id.into(),
154 };
155
156 self.save_backup_metadata(&backup).await?;
158
159 self.cleanup_old_backups(file_path).await?;
161
162 tracing::info!("Created backup for {:?} at {:?}", file_path, backup_path);
163
164 Ok(backup)
165 }
166
167 async fn unique_backup_path(&self, stem: &str) -> PathBuf {
170 let mut candidate = self.backup_dir.join(stem);
171 let mut suffix: u32 = 0;
172 while tokio::fs::symlink_metadata(&candidate).await.is_ok() {
173 suffix += 1;
174 candidate = self.backup_dir.join(format!("{stem}_{suffix}"));
175 }
176 candidate
177 }
178
179 fn safe_filename(&self, path: &Path) -> String {
181 path.to_string_lossy()
182 .replace(['/', '\\', ':', '.'], "_")
183 .trim_start_matches('_')
184 .to_string()
185 }
186
187 async fn save_backup_metadata(&self, backup: &DotfileBackup) -> Result<()> {
189 let index_path = self.backup_dir.join("backups.json");
190
191 let mut backups = self.load_backup_index().await.unwrap_or_default();
192 backups.push(backup.clone());
193
194 write_private_json_file(&index_path, &backups)
195 .await
196 .with_context(|| format!("Failed to write backup index: {index_path:?}"))?;
197
198 Ok(())
199 }
200
201 async fn load_backup_index(&self) -> Result<Vec<DotfileBackup>> {
203 let index_path = self.backup_dir.join("backups.json");
204
205 if !tokio::fs::symlink_metadata(&index_path)
206 .await
207 .is_ok_and(|metadata| metadata.is_file())
208 {
209 return Ok(Vec::new());
210 }
211
212 let backups: Vec<DotfileBackup> = read_private_json_file(&index_path)
213 .await
214 .with_context(|| format!("Failed to parse backup index: {index_path:?}"))?;
215
216 Ok(backups)
217 }
218
219 async fn cleanup_old_backups(&self, file_path: &Path) -> Result<()> {
221 let backups = self.load_backup_index().await?;
222 let file_path_str = file_path.to_string_lossy();
223
224 let mut file_backups: Vec<_> = backups.iter().filter(|b| b.original_path == file_path_str).collect();
226
227 file_backups.sort_by_key(|a| std::cmp::Reverse(a.created_at));
228
229 for backup in file_backups.iter().skip(self.max_backups) {
231 let backup_path = Path::new(&backup.backup_path);
232 if self.is_managed_backup_path(backup_path)
233 && tokio::fs::symlink_metadata(backup_path)
234 .await
235 .is_ok_and(|metadata| metadata.is_file())
236 {
237 if let Err(e) = tokio::fs::remove_file(backup_path).await {
238 tracing::warn!("Failed to remove old backup {:?}: {}", backup_path, e);
239 } else {
240 tracing::debug!("Removed old backup: {:?}", backup_path);
241 }
242 }
243 }
244
245 let mut remaining = Vec::with_capacity(backups.len());
248 for b in backups {
249 if b.original_path != file_path_str {
250 remaining.push(b);
251 continue;
252 }
253 if self.is_managed_backup_path(Path::new(&b.backup_path))
254 && tokio::fs::symlink_metadata(&b.backup_path)
255 .await
256 .is_ok_and(|metadata| metadata.is_file())
257 {
258 remaining.push(b);
259 }
260 }
261
262 let index_path = self.backup_dir.join("backups.json");
263 write_private_json_file(&index_path, &remaining)
264 .await
265 .with_context(|| "Failed to update backup index")?;
266
267 Ok(())
268 }
269
270 pub async fn get_backups_for_file(&self, file_path: &Path) -> Result<Vec<DotfileBackup>> {
272 let backups = self.load_backup_index().await?;
273 let file_path_str = file_path.to_string_lossy();
274
275 let mut file_backups: Vec<_> = backups.into_iter().filter(|b| b.original_path == file_path_str).collect();
276
277 file_backups.sort_by_key(|a| std::cmp::Reverse(a.created_at));
278
279 Ok(file_backups)
280 }
281
282 pub async fn get_latest_backup(&self, file_path: &Path) -> Result<Option<DotfileBackup>> {
284 let backups = self.get_backups_for_file(file_path).await?;
285 Ok(backups.into_iter().next())
286 }
287
288 pub async fn list_all_backups(&self) -> Result<Vec<DotfileBackup>> {
290 self.load_backup_index().await
291 }
292
293 pub async fn restore_latest(&self, file_path: &Path) -> Result<()> {
295 let backup = self
296 .get_latest_backup(file_path)
297 .await?
298 .ok_or_else(|| anyhow::anyhow!("No backup found for: {file_path:?}"))?;
299
300 backup.restore().await
301 }
302
303 pub async fn verify_all_backups(&self) -> Result<Vec<(DotfileBackup, bool)>> {
305 let backups = self.load_backup_index().await?;
306 let mut results = Vec::new();
307
308 for backup in backups {
309 let backup_path = Path::new(&backup.backup_path);
310 let valid = if self.is_managed_backup_path(backup_path)
311 && tokio::fs::symlink_metadata(backup_path)
312 .await
313 .is_ok_and(|metadata| metadata.is_file())
314 {
315 match read_private_file_no_follow(backup_path).await {
316 Ok(content) => {
317 let hash = calculate_sha256(&content);
318 hash == backup.content_hash
319 }
320 Err(_) => false,
321 }
322 } else {
323 false
324 };
325 results.push((backup, valid));
326 }
327
328 Ok(results)
329 }
330
331 fn is_managed_backup_path(&self, path: &Path) -> bool {
332 path.parent() == Some(self.backup_dir.as_path()) && path.file_name().is_some_and(|name| name != "backups.json")
333 }
334}
335
336#[cfg(test)]
337mod tests {
338 use super::*;
339 use tempfile::tempdir;
340
341 #[tokio::test]
342 async fn test_backup_creation() {
343 let dir = tempdir().unwrap();
344 let backup_dir = dir.path().join("backups");
345 let test_file = dir.path().join(".testrc");
346
347 tokio::fs::write(&test_file, "test content").await.unwrap();
349
350 let manager = BackupManager::new(&backup_dir, 5).await.unwrap();
351 let backup = manager.create_backup(&test_file, "test backup", "test-session").await.unwrap();
352
353 assert_eq!(backup.original_path, test_file.to_string_lossy());
354 assert!(Path::new(&backup.backup_path).exists());
355 }
356
357 #[tokio::test]
358 async fn test_backup_restore() {
359 let dir = tempdir().unwrap();
360 let backup_dir = dir.path().join("backups");
361 let test_file = dir.path().join(".testrc");
362
363 let original_content = "original content";
365 tokio::fs::write(&test_file, original_content).await.unwrap();
366
367 let manager = BackupManager::new(&backup_dir, 5).await.unwrap();
368 let backup = manager
369 .create_backup(&test_file, "before modification", "test-session")
370 .await
371 .unwrap();
372
373 tokio::fs::write(&test_file, "modified content").await.unwrap();
375
376 backup.restore().await.unwrap();
378
379 let restored = tokio::fs::read_to_string(&test_file).await.unwrap();
381 assert_eq!(restored, original_content);
382 }
383
384 #[tokio::test]
385 async fn test_unique_backup_path_appends_counter_on_collision() {
386 let dir = tempdir().unwrap();
387 let backup_dir = dir.path().join("backups");
388 let manager = BackupManager::new(&backup_dir, 5).await.unwrap();
389
390 assert_eq!(manager.unique_backup_path("a.backup").await, backup_dir.join("a.backup"));
391
392 tokio::fs::write(backup_dir.join("a.backup"), "taken").await.unwrap();
393 assert_eq!(manager.unique_backup_path("a.backup").await, backup_dir.join("a.backup_1"));
394
395 tokio::fs::write(backup_dir.join("a.backup_1"), "taken").await.unwrap();
396 assert_eq!(manager.unique_backup_path("a.backup").await, backup_dir.join("a.backup_2"));
397 }
398
399 #[tokio::test]
400 async fn test_backup_cleanup() {
401 let dir = tempdir().unwrap();
402 let backup_dir = dir.path().join("backups");
403 let test_file = dir.path().join(".testrc");
404
405 tokio::fs::write(&test_file, "test").await.unwrap();
406
407 let manager = BackupManager::new(&backup_dir, 2).await.unwrap();
408
409 for i in 0..5 {
411 tokio::fs::write(&test_file, format!("content {i}")).await.unwrap();
412 manager
413 .create_backup(&test_file, format!("backup {i}"), "test-session")
414 .await
415 .unwrap();
416 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
417 }
418
419 let backups = manager.get_backups_for_file(&test_file).await.unwrap();
420 assert_eq!(backups.len(), 2);
421 }
422}