fix(backup): validate restore inputs and allow recovery retries

This commit is contained in:
Tunglies
2026-11-30 19:45:45 +08:00
parent 1b7d2a3fbe
commit c22722e9ca
5 changed files with 175 additions and 22 deletions
+1 -1
View File
@@ -65,7 +65,7 @@ impl<R: Read + Seek> ValidatedBackup<R> {
Ok(Self { zip })
}
pub fn extract_to(mut self, destination: &Path) -> Result<(), ArchiveError> {
pub fn extract_to(&mut self, destination: &Path) -> Result<(), ArchiveError> {
self.zip.extract(destination)?;
Ok(())
}
+41 -5
View File
@@ -1,20 +1,56 @@
use anyhow::{Result, anyhow};
use clash_verge_profile_store::RECOVERY_JOURNAL_NAME;
use std::sync::OnceLock;
use parking_lot::Mutex;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
static PROFILE_IO: RwLock<()> = RwLock::const_new(());
static BLOCKED: OnceLock<String> = OnceLock::new();
static BLOCKED: Mutex<Option<StorageBlock>> = Mutex::new(None);
enum StorageBlock {
Transaction(String),
Restore(String),
}
pub(crate) fn check() -> Result<()> {
match BLOCKED.get() {
Some(reason) => Err(anyhow!("Profile storage requires recovery before use: {reason}")),
match BLOCKED.lock().as_ref() {
Some(StorageBlock::Transaction(reason) | StorageBlock::Restore(reason)) => {
Err(anyhow!("Profile storage requires recovery before use: {reason}"))
}
None => Ok(()),
}
}
pub(crate) fn block(error: &anyhow::Error) {
let _ = BLOCKED.set(format!("{error:#}"));
let mut blocked = BLOCKED.lock();
if !matches!(*blocked, Some(StorageBlock::Transaction(_))) {
*blocked = Some(StorageBlock::Transaction(format!("{error:#}")));
}
}
pub(crate) fn block_restore(error: &anyhow::Error) {
let mut blocked = BLOCKED.lock();
if !matches!(*blocked, Some(StorageBlock::Transaction(_))) {
*blocked = Some(StorageBlock::Restore(format!("{error:#}")));
}
}
pub(crate) async fn write_for_restore() -> Result<(RwLockWriteGuard<'static, ()>, bool)> {
let guard = PROFILE_IO.write().await;
let retry = match BLOCKED.lock().as_ref() {
Some(StorageBlock::Transaction(reason)) => {
return Err(anyhow!("Profile storage requires recovery before use: {reason}"));
}
Some(StorageBlock::Restore(_)) => true,
None => false,
};
Ok((guard, retry))
}
pub(crate) fn finish_restore(_guard: &RwLockWriteGuard<'_, ()>) {
let mut blocked = BLOCKED.lock();
if matches!(*blocked, Some(StorageBlock::Restore(_))) {
*blocked = None;
}
}
pub(crate) async fn read() -> Result<RwLockReadGuard<'static, ()>> {
+5 -1
View File
@@ -82,6 +82,10 @@ pub(crate) async fn load_profiles() -> IProfiles {
pub(crate) async fn load_profiles_checked() -> Result<IProfiles> {
profile_storage::check()?;
load_profiles_unlocked().await
}
pub(crate) async fn load_profiles_unlocked() -> Result<IProfiles> {
let mut profiles: IProfiles = help::read_yaml(&dirs::profiles_path()?).await?;
let items = profiles.items.get_or_insert_with(Vec::new);
let mut home_changed = false;
@@ -179,7 +183,7 @@ async fn patch_item(profiles: &mut IProfiles, uid: &str, item: &PrfItem) -> Resu
bail!("failed to find the profile item \"uid:{uid}\"")
}
fn validate_profile_file(file: &str) -> Result<()> {
pub(crate) fn validate_profile_file(file: &str) -> Result<()> {
let mut components = Path::new(file).components();
if file.is_empty()
|| file.contains('/')
+126 -14
View File
@@ -1,20 +1,29 @@
use crate::{
config::{Config, IClashTemp, IVerge, profiles::load_profiles_checked},
config::{
Config, IClashTemp, IProfiles, IVerge, profile_storage,
profiles::{load_profiles_unlocked, validate_profile_file},
},
core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
process::AsyncHandler,
utils::{
dirs::{PathBufExec as _, app_home_dir, local_backup_dir, verge_path},
dirs::{
PROFILE_YAML, PROFILES_DIR, PathBufExec as _, VERGE_CONFIG, app_home_dir, local_backup_dir, verge_path,
},
help,
},
};
use anyhow::{Result, anyhow};
use anyhow::{Context as _, Result, anyhow};
use chrono::Utc;
use clash_verge_backup_archive::ValidatedBackup;
use clash_verge_draft::DraftConflict;
use clash_verge_logging::{Type, logging};
use clash_verge_profile_store::RECOVERY_ENTRY_NAMES;
use reqwest_dav::list_cmd::ListFile;
use serde::Serialize;
use std::{fs::File, path::PathBuf};
use std::{
fs::File,
path::{Path, PathBuf},
};
use tokio::fs;
use tristr::alias::String;
@@ -41,19 +50,25 @@ async fn finalize_restored_verge_config(
let draft = &profiles_draft;
profiles_draft
.with_data_modify(|_| async move {
*guard = Some(crate::config::profile_storage::write().await?);
let (profiles, mut restored) = restore_files(archive).await?;
let (io_guard, retry) = profile_storage::write_for_restore().await?;
*guard = Some(io_guard);
let (profiles, mut restored) = restore_files(archive, retry).await?;
restored.webdav_url = webdav_url;
restored.webdav_username = webdav_username;
restored.webdav_password = webdav_password;
if let Err(error) = restored.save_file().await {
crate::config::profile_storage::block(&error);
profile_storage::block_restore(&error);
return Err(error);
}
draft.discard();
Ok((profiles, restored))
})
.await?
.await
.inspect_err(|error: &anyhow::Error| {
if error.is::<DraftConflict>() {
profile_storage::block_restore(error);
}
})?
};
let restored_clash = IClashTemp::new().await;
let clash_draft = Config::clash().await;
@@ -67,6 +82,9 @@ async fn finalize_restored_verge_config(
*d = restored.clone();
});
verge_draft.apply();
if let Some(guard) = &profile_guard {
profile_storage::finish_restore(guard);
}
drop(profile_guard);
auto_backup::publish_settings(&verge_draft.data_arc());
@@ -142,32 +160,80 @@ pub async fn delete_webdav_backup(filename: String) -> Result<()> {
})
}
async fn restore_files(archive: ValidatedBackup<File>) -> Result<(crate::config::IProfiles, IVerge)> {
async fn restore_config_path(staged: &Path, home: &Path, name: &str, retry: bool) -> Result<PathBuf> {
let path = staged.join(name);
if !retry && !fs::try_exists(&path).await? {
return Ok(home.join(name));
}
Ok(path)
}
async fn validate_restore(
mut archive: ValidatedBackup<File>,
home_dir: &Path,
retry: bool,
) -> Result<ValidatedBackup<File>> {
let staging_root = home_dir.to_owned();
let (staged, archive) = AsyncHandler::spawn_blocking(move || -> Result<_> {
let staged = tempfile::tempdir_in(staging_root)?;
archive.extract_to(staged.path())?;
Ok((staged, archive))
})
.await
.map_err(|join| anyhow!("backup staging task failed: {join}"))??;
let validated: Result<()> = async {
let verge = restore_config_path(staged.path(), home_dir, VERGE_CONFIG, retry).await?;
let profiles_path = restore_config_path(staged.path(), home_dir, PROFILE_YAML, retry).await?;
help::read_yaml::<IVerge>(&verge).await?;
let profiles: IProfiles = help::read_yaml(&profiles_path).await?;
if retry {
let bodies = staged.path().join(PROFILES_DIR);
for file in profiles.items.iter().flatten().filter_map(|item| item.file.as_deref()) {
validate_profile_file(file)?;
let body = fs::symlink_metadata(bodies.join(file))
.await
.with_context(|| format!("failed to inspect recovery backup profile body {file}"))?;
anyhow::ensure!(body.is_file(), "recovery backup profile body {file} is not a file");
}
}
Ok(())
}
.await;
AsyncHandler::spawn_blocking(move || drop(staged)).await?;
validated?;
Ok(archive)
}
async fn restore_files(archive: ValidatedBackup<File>, retry: bool) -> Result<(IProfiles, IVerge)> {
let home_dir = app_home_dir()?;
let mut archive = validate_restore(archive, &home_dir, retry).await?;
AsyncHandler::spawn_blocking(move || -> Result<()> {
let extracted = archive.extract_to(&home_dir).map_err(anyhow::Error::from);
if let Err(error) = &extracted {
crate::config::profile_storage::block(error);
profile_storage::block_restore(error);
}
extracted
})
.await
.map_err(|join| anyhow!("backup extraction task failed: {join}"))??;
.map_err(|join| {
let error = anyhow!("backup extraction task failed: {join}");
profile_storage::block_restore(&error);
error
})??;
let loaded = async {
let verge = help::read_yaml::<IVerge>(&verge_path()?).await?;
let profiles = load_profiles_checked().await?;
let profiles = load_profiles_unlocked().await?;
Ok((profiles, verge))
}
.await;
if let Err(error) = &loaded {
crate::config::profile_storage::block(error);
profile_storage::block_restore(error);
}
loaded
}
/// Backup creation strips the WebDAV credentials, so the live ones are kept.
async fn restore_backup_archive(path: PathBuf) -> Result<()> {
crate::config::profile_storage::check()?;
let archive = AsyncHandler::spawn_blocking(move || -> Result<_> {
Ok(ValidatedBackup::open(File::open(path)?, RECOVERY_ENTRY_NAMES)?)
})
@@ -398,3 +464,49 @@ pub async fn export_local_backup(filename: String, destination: String) -> Resul
.map_err(|err| anyhow!("Failed to export backup file: {err:#}"))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use clash_verge_backup_archive::BackupWriter;
use std::io::Write as _;
#[tokio::test]
async fn validates_config_before_replacing_live_files() -> Result<()> {
let home = tempfile::tempdir()?;
let path = home.path().join(PROFILE_YAML);
let live = b"items: []\n";
fs::write(&path, live).await?;
fs::write(home.path().join(VERGE_CONFIG), b"{}\n").await?;
let open_backup = |index: Option<&[u8]>, include_body: bool| -> Result<_> {
let file = tempfile::tempfile()?;
let mut writer = BackupWriter::new(file)?;
writer.start_file(VERGE_CONFIG)?.write_all(b"{}\n")?;
if let Some(index) = index {
writer.start_file(PROFILE_YAML)?.write_all(index)?;
}
if include_body {
writer.start_profile("r.yaml")?.write_all(b"proxies: []\n")?;
}
Ok(ValidatedBackup::open(writer.finish()?, RECOVERY_ENTRY_NAMES)?)
};
let invalid = open_backup(Some(b"items: invalid\n"), false)?;
assert!(validate_restore(invalid, home.path(), false).await.is_err());
assert_eq!(fs::read(&path).await?, live);
validate_restore(open_backup(None, false)?, home.path(), false).await?;
assert!(
validate_restore(open_backup(None, false)?, home.path(), true)
.await
.is_err()
);
let index = b"items: [{uid: r, type: remote, file: r.yaml}]\n";
assert!(
validate_restore(open_backup(Some(index), false)?, home.path(), true)
.await
.is_err()
);
validate_restore(open_backup(Some(index), true)?, home.path(), true).await?;
Ok(())
}
}
+2 -1
View File
@@ -21,6 +21,7 @@ pub static BACKUP_DIR: &str = "clash-verge-rev-backup-dev";
pub static CLASH_CONFIG: &str = "config.yaml";
pub static VERGE_CONFIG: &str = "verge.yaml";
pub static PROFILE_YAML: &str = "profiles.yaml";
pub static PROFILES_DIR: &str = "profiles";
/// Marks that the one-shot raise of too-short auto-update intervals has already run.
pub static UPDATE_INTERVAL_MIGRATED: &str = ".update-interval-migrated";
@@ -48,7 +49,7 @@ pub fn app_resources_dir() -> Result<PathBuf> {
}
pub fn app_profiles_dir() -> Result<PathBuf> {
Ok(app_home_dir()?.join("profiles"))
Ok(app_home_dir()?.join(PROFILES_DIR))
}
pub fn app_icons_dir() -> Result<PathBuf> {