diff --git a/apps/desktop/src/components/migration/SecurityMigrationWizard.vue b/apps/desktop/src/components/migration/SecurityMigrationWizard.vue index 831ebfe804..c9fed2901d 100644 --- a/apps/desktop/src/components/migration/SecurityMigrationWizard.vue +++ b/apps/desktop/src/components/migration/SecurityMigrationWizard.vue @@ -29,6 +29,8 @@ const errorAdviceKey = computed(() => { case "SECRET_KEY_MISMATCH": case "KEY_FILE_UNAVAILABLE": case "KEY_PROVIDER_UNAVAILABLE": + case "KEYRING_ACCESS_FAILED": + case "KEYRING_WRITE_FAILED": return "migration.errors.keyProviderAdvice"; case "BACKUP_FAILED": return "migration.errors.backupAdvice"; diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts index b412207bbb..8131b1c57b 100644 --- a/apps/desktop/src/i18n/locales/az.ts +++ b/apps/desktop/src/i18n/locales/az.ts @@ -10598,7 +10598,7 @@ export default withEnglishFallback({ persistentKeyAdvice: "Davamlı açar qurun və vəziyyəti yenidən yoxlayın.", cleanupAdvice: "Ehtiyat qovluğunun icazələrini yoxlayın və yenidən cəhd edin.", genericAdvice: "Problemi həll edib yenidən cəhd edin.", - keyProviderAdvice: "Açar zəncirinə girişə icazə verin və ya davamlı açar faylı qurun.", + keyProviderAdvice: "DBX-in etimadnamə yaddaşına daxil ola bildiyini yoxlayın. Problem davam edərsə DBX_SECRET_KEY_FILE qurun. Mövcud DBX açarını silməyin.", backupAdvice: "Məlumat qovluğunun yazıla bildiyini və boş yer olduğunu yoxlayın.", jsonAdvice: "Göstərilən faylı düzəldib yenidən cəhd edin.", verifyAdvice: "Yoxlama uğurlu olana qədər ehtiyat nüsxəni saxlayın.", diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts index e0a880f9e5..31796e538a 100644 --- a/apps/desktop/src/i18n/locales/en.ts +++ b/apps/desktop/src/i18n/locales/en.ts @@ -11515,7 +11515,7 @@ export default { persistentKeyAdvice: "Configure DBX_SECRET_KEY_FILE or DBX_SECRET_KEY with a persistent key, then retry the status check.", cleanupAdvice: "Check backup directory permissions and retry deleting the backup. Your migrated data is ready to use.", genericAdvice: "Fix the issue above and retry. Your original data is still available.", - keyProviderAdvice: "Allow DBX to access the keychain or provide a persistent DBX_SECRET_KEY_FILE.", + keyProviderAdvice: "Check that DBX can access its credential store. If access still fails, configure a persistent DBX_SECRET_KEY_FILE. Do not delete the existing DBX key item.", backupAdvice: "Check that the data directory is writable and has enough free space.", jsonAdvice: "Repair the reported legacy JSON file, then retry the migration.", verifyAdvice: "Keep the backup and retry. Do not delete migration backups until verification succeeds.", diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts index 461d3297c4..ea1215ccfb 100644 --- a/apps/desktop/src/i18n/locales/es.ts +++ b/apps/desktop/src/i18n/locales/es.ts @@ -10862,7 +10862,7 @@ export default withEnglishFallback({ persistentKeyAdvice: "Configura una clave persistente y vuelve a comprobar el estado.", cleanupAdvice: "Comprueba los permisos del directorio y vuelve a intentarlo.", genericAdvice: "Soluciona el problema y vuelve a intentarlo.", - keyProviderAdvice: "Permite el acceso al llavero o configura un archivo de clave persistente.", + keyProviderAdvice: "Comprueba que DBX pueda acceder a su almacén de credenciales. Si sigue fallando, configura DBX_SECRET_KEY_FILE. No elimines la clave existente de DBX.", backupAdvice: "Comprueba que el directorio permite escribir y tiene espacio suficiente.", jsonAdvice: "Repara el archivo indicado y vuelve a intentarlo.", verifyAdvice: "Conserva la copia hasta que la verificación sea correcta.", diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts index 5d11947864..4021c85a47 100644 --- a/apps/desktop/src/i18n/locales/it.ts +++ b/apps/desktop/src/i18n/locales/it.ts @@ -10787,7 +10787,7 @@ export default withEnglishFallback({ persistentKeyAdvice: "Configura una chiave persistente e ricontrolla lo stato.", cleanupAdvice: "Controlla i permessi della directory e riprova.", genericAdvice: "Risolvi il problema e riprova.", - keyProviderAdvice: "Consenti l'accesso al portachiavi o configura un file chiave persistente.", + keyProviderAdvice: "Verifica che DBX possa accedere al proprio archivio delle credenziali. Se l'errore persiste, configura DBX_SECRET_KEY_FILE. Non eliminare la chiave DBX esistente.", backupAdvice: "Controlla i permessi di scrittura e lo spazio disponibile.", jsonAdvice: "Ripara il file indicato e riprova.", verifyAdvice: "Conserva il backup finché la verifica non riesce.", diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts index 8a5663f412..253941c71f 100644 --- a/apps/desktop/src/i18n/locales/ja.ts +++ b/apps/desktop/src/i18n/locales/ja.ts @@ -10825,7 +10825,7 @@ export default withEnglishFallback({ persistentKeyAdvice: "永続鍵を設定してから状態確認を再試行してください。", cleanupAdvice: "バックアップディレクトリの権限を確認して削除を再試行してください。移行済みデータは使用できます。", genericAdvice: "問題を解決してから再試行してください。元のデータは保持されています。", - keyProviderAdvice: "キーチェーンへのアクセスを許可するか、永続鍵ファイルを設定してください。", + keyProviderAdvice: "DBX が資格情報ストアにアクセスできることを確認してください。それでも失敗する場合は DBX_SECRET_KEY_FILE を設定してください。既存の DBX 鍵を削除しないでください。", backupAdvice: "データディレクトリの書き込み権限と空き容量を確認してください。", jsonAdvice: "表示されたファイルを修復してから移行を再試行してください。", verifyAdvice: "バックアップを保持したまま再試行してください。検証が成功するまで削除しないでください。", diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts index fe2b3cee7c..7ee400dccf 100644 --- a/apps/desktop/src/i18n/locales/ko.ts +++ b/apps/desktop/src/i18n/locales/ko.ts @@ -10234,7 +10234,7 @@ export default withEnglishFallback({ persistentKeyAdvice: "영구 키를 설정한 후 상태 확인을 다시 시도하세요.", cleanupAdvice: "백업 디렉터리 권한을 확인한 후 다시 시도하세요.", genericAdvice: "문제를 해결한 후 다시 시도하세요.", - keyProviderAdvice: "키체인 접근을 허용하거나 영구 키 파일을 설정하세요.", + keyProviderAdvice: "DBX가 자격 증명 저장소에 접근할 수 있는지 확인하세요. 계속 실패하면 DBX_SECRET_KEY_FILE을 설정하세요. 기존 DBX 키 항목을 삭제하지 마세요.", backupAdvice: "데이터 디렉터리의 쓰기 권한과 여유 공간을 확인하세요.", jsonAdvice: "표시된 파일을 수정한 후 다시 시도하세요.", verifyAdvice: "확인이 성공할 때까지 백업을 보관하세요.", diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts index fbb94f5b15..a45e0c0914 100644 --- a/apps/desktop/src/i18n/locales/pt-BR.ts +++ b/apps/desktop/src/i18n/locales/pt-BR.ts @@ -10787,7 +10787,7 @@ export default withEnglishFallback({ persistentKeyAdvice: "Configure uma chave persistente e verifique o estado novamente.", cleanupAdvice: "Verifique as permissões do diretório e tente novamente.", genericAdvice: "Resolva o problema e tente novamente.", - keyProviderAdvice: "Permita o acesso ao chaveiro ou configure um arquivo de chave persistente.", + keyProviderAdvice: "Verifique se o DBX consegue acessar seu armazenamento de credenciais. Se continuar falhando, configure DBX_SECRET_KEY_FILE. Não exclua a chave DBX existente.", backupAdvice: "Verifique as permissões de gravação e o espaço disponível.", jsonAdvice: "Corrija o arquivo indicado e tente novamente.", verifyAdvice: "Mantenha o backup até a verificação ser concluída.", diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts index 24a14d8f83..ec7a627e15 100644 --- a/apps/desktop/src/i18n/locales/ru.ts +++ b/apps/desktop/src/i18n/locales/ru.ts @@ -11916,7 +11916,7 @@ export default withEnglishFallback({ persistentKeyAdvice: "Настройте DBX_SECRET_KEY_FILE или DBX_SECRET_KEY с постоянным ключом, затем повторите проверку статуса.", cleanupAdvice: "Проверьте права доступа к каталогу резервных копий и повторите удаление резервной копии. Ваши мигрированные данные готовы к использованию.", genericAdvice: "Устраните указанную выше проблему и повторите. Ваши исходные данные по-прежнему доступны.", - keyProviderAdvice: "Разрешите DBX доступ к связке ключей или укажите постоянный DBX_SECRET_KEY_FILE.", + keyProviderAdvice: "Проверьте, что DBX может получить доступ к хранилищу учётных данных. Если ошибка сохраняется, настройте DBX_SECRET_KEY_FILE. Не удаляйте существующий ключ DBX.", backupAdvice: "Проверьте, что каталог данных доступен для записи и имеет достаточно свободного места.", jsonAdvice: "Исправьте указанный устаревший JSON-файл, затем повторите миграцию.", verifyAdvice: "Сохраните резервную копию и повторите. Не удаляйте резервные копии миграции, пока проверка не завершится успешно.", diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts index 178609839a..b75bf40752 100644 --- a/apps/desktop/src/i18n/locales/tr.ts +++ b/apps/desktop/src/i18n/locales/tr.ts @@ -10479,7 +10479,7 @@ export default withEnglishFallback({ persistentKeyAdvice: "Kalıcı anahtar yapılandırın ve durumu yeniden denetleyin.", cleanupAdvice: "Yedek dizini izinlerini kontrol edip yeniden deneyin.", genericAdvice: "Sorunu düzeltip yeniden deneyin.", - keyProviderAdvice: "Anahtarlık erişimine izin verin veya kalıcı anahtar dosyası yapılandırın.", + keyProviderAdvice: "DBX'in kimlik bilgileri deposuna erişebildiğini kontrol edin. Sorun sürerse DBX_SECRET_KEY_FILE yapılandırın. Mevcut DBX anahtarını silmeyin.", backupAdvice: "Veri dizininin yazılabilir olduğunu ve yeterli alan bulunduğunu kontrol edin.", jsonAdvice: "Belirtilen dosyayı düzeltip yeniden deneyin.", verifyAdvice: "Doğrulama başarılı olana kadar yedeği saklayın.", diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts index 99576ac62d..b226067b85 100644 --- a/apps/desktop/src/i18n/locales/zh-CN.ts +++ b/apps/desktop/src/i18n/locales/zh-CN.ts @@ -11475,7 +11475,7 @@ export default withEnglishFallback({ persistentKeyAdvice: "请配置持久化的 DBX_SECRET_KEY_FILE 或 DBX_SECRET_KEY,然后重新检查状态。", cleanupAdvice: "请检查备份目录权限后重试删除备份,迁移后的数据可正常使用。", genericAdvice: "请修复上述问题后重试,原始数据仍然保留。", - keyProviderAdvice: "请允许 DBX 访问钥匙串,或配置持久化的 DBX_SECRET_KEY_FILE。", + keyProviderAdvice: "请检查 DBX 是否能够访问其密钥存储;如果仍然失败,请配置持久化的 DBX_SECRET_KEY_FILE。不要删除已有的 DBX 密钥项。", backupAdvice: "请确认数据目录可写且有足够的剩余空间。", jsonAdvice: "请修复提示的历史 JSON 文件后重试迁移。", verifyAdvice: "请保留备份并重试,验证成功前不要删除迁移备份。", diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts index c6fd89f51b..cbc61b9316 100644 --- a/apps/desktop/src/i18n/locales/zh-TW.ts +++ b/apps/desktop/src/i18n/locales/zh-TW.ts @@ -10793,7 +10793,7 @@ export default withEnglishFallback({ persistentKeyAdvice: "請設定持久化金鑰後重新檢查狀態。", cleanupAdvice: "請檢查備份目錄權限後重試。", genericAdvice: "請修正問題後重試。", - keyProviderAdvice: "請允許存取鑰匙圈或設定持久化金鑰檔案。", + keyProviderAdvice: "請檢查 DBX 是否能夠存取其憑證儲存;如果仍然失敗,請設定持久化的 DBX_SECRET_KEY_FILE。請勿刪除現有的 DBX 金鑰項目。", backupAdvice: "請確認資料目錄可寫入且有足夠空間。", jsonAdvice: "請修復提示的檔案後重試。", verifyAdvice: "驗證成功前請保留備份。", diff --git a/crates/dbx-core/src/persistence/storage.rs b/crates/dbx-core/src/persistence/storage.rs index 9cb5301448..980f7f7fad 100644 --- a/crates/dbx-core/src/persistence/storage.rs +++ b/crates/dbx-core/src/persistence/storage.rs @@ -207,6 +207,7 @@ pub struct Storage { /// round-trips to the OS credential store, so hydrating N stored secrets /// used to mean N credential-store accesses on the startup path. secret_codec_cache: Arc>>, + migration_failure: Arc>>, } /// Key material plus the digest of every key file it was resolved from. @@ -215,6 +216,14 @@ struct CachedSecretCodec { key_files: Vec<(PathBuf, Option<[u8; 32]>)>, } +#[derive(Clone)] +struct MigrationFailure { + code: String, + backup_path: Option, +} + +const MIGRATION_LOCK_FILE: &str = ".dbx-secret-migration.lock"; + pub const SECRET_STORE_MIGRATION_ID: &str = "secret-store-v1"; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] @@ -1182,7 +1191,15 @@ fn migration_backup_paths(counts: &serde_json::Value) -> Result, Str } fn migration_error_code(error: &str) -> &'static str { - if error.contains("MISSING_MANAGED_KEY") { + if error.contains("MIGRATION_STATE_WRITE_FAILED") { + "MIGRATION_STATE_WRITE_FAILED" + } else if error.contains("MIGRATION_RESTORE_FAILED") { + "MIGRATION_RESTORE_FAILED" + } else if error.contains("MIGRATION_INTERRUPTED") { + "MIGRATION_INTERRUPTED" + } else if error.contains("BACKUP_FAILED") { + "BACKUP_FAILED" + } else if error.contains("MISSING_MANAGED_KEY") { "MISSING_MANAGED_KEY" } else if error.contains("ENCRYPTED_DATA_KEY_MISSING") { "ENCRYPTED_DATA_KEY_MISSING" @@ -1192,6 +1209,10 @@ fn migration_error_code(error: &str) -> &'static str { "SECRET_KEY_INVALID" } else if error.contains("KEY_FILE_UNAVAILABLE") { "KEY_FILE_UNAVAILABLE" + } else if error.contains("KEYRING_ACCESS_FAILED") { + "KEYRING_ACCESS_FAILED" + } else if error.contains("KEYRING_WRITE_FAILED") { + "KEYRING_WRITE_FAILED" } else if error.contains("MISSING_EXTERNAL_KEY") || error.contains("MISSING_PERSISTENT_KEY") { "MISSING_EXTERNAL_KEY" } else if error.contains("KEY_PROVIDER_UNAVAILABLE") { @@ -1209,11 +1230,22 @@ fn migration_error_code(error: &str) -> &'static str { fn migration_safe_message(code: &str, _error: &str) -> String { match code { + "MIGRATION_STATE_WRITE_FAILED" => { + "Could not save the migration failure status; keep the backup and retry".to_string() + } + "MIGRATION_RESTORE_FAILED" => "Could not restore the database backup; keep the backup for recovery".to_string(), + "MIGRATION_INTERRUPTED" => "The previous migration was interrupted; keep the backup and retry".to_string(), "MISSING_MANAGED_KEY" => "A managed data-directory secret key is required".to_string(), "ENCRYPTED_DATA_KEY_MISSING" => "The key for existing encrypted data is missing".to_string(), "SECRET_KEY_MISMATCH" => "The configured secret key cannot decrypt existing data".to_string(), "SECRET_KEY_INVALID" => "The configured secret key is invalid".to_string(), "KEY_FILE_UNAVAILABLE" => "The configured secret key file is unavailable".to_string(), + "KEYRING_ACCESS_FAILED" => { + "The platform credential store refused access to the DBX secret-store key".to_string() + } + "KEYRING_WRITE_FAILED" => { + "DBX could not save the secret-store key in the platform credential store".to_string() + } "MISSING_EXTERNAL_KEY" => "An external secret key is required".to_string(), "BACKUP_FAILED" => "Could not create a migration backup".to_string(), "LEGACY_JSON_INVALID" => "A legacy configuration file could not be read".to_string(), @@ -1269,6 +1301,7 @@ impl Storage { secret_key_policy: SecretKeyPolicy::PlatformDefault, secret_key_creation_allowed: true, secret_codec_cache: Arc::new(Mutex::new(None)), + migration_failure: Arc::new(Mutex::new(None)), }; // Best-effort: switching journal mode is itself a lock-sensitive // operation, so a transient failure here (e.g. another process @@ -1324,9 +1357,7 @@ impl Storage { // files are unchanged across the resolve. A pair taken after resolving // could combine a stale codec with fresh digests, which the use-time // digest check would then never reject. - if self.key_file_digests() == key_files { - self.cache_secret_codec(codec, key_files); - } + self.cache_secret_codec_if_unchanged(codec, key_files); Ok(codec) } @@ -1348,6 +1379,14 @@ impl Storage { *self.secret_codec_cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(entry); } + fn cache_secret_codec_if_unchanged(&self, codec: SecretCodec, before: Vec<(PathBuf, Option<[u8; 32]>)>) { + if self.key_file_digests() == before { + self.cache_secret_codec(codec, before); + } else { + self.invalidate_secret_codec(); + } + } + fn invalidate_secret_codec(&self) { *self.secret_codec_cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = None; } @@ -1489,7 +1528,20 @@ impl Storage { pub async fn inspect_data_migration(&self) -> Result { let files = self.legacy_json_files().await?; - let stored = self.load_migration_state().await?; + let mut stored = self.load_migration_state().await?; + let failure = self.migration_failure.lock().unwrap_or_else(|p| p.into_inner()).clone(); + if let Some(failure) = failure { + stored.state = MigrationState::Failed; + stored.error_message = Some(migration_safe_message(&failure.code, "")); + stored.error_code = Some(failure.code); + stored.backup_path = failure.backup_path.or(stored.backup_path); + } else if stored.state == MigrationState::Running && !self.migration_is_active()? { + // A process exit releases the lock. Report interruption without + // modifying the database during a status request. + stored.state = MigrationState::Failed; + stored.error_code = Some("MIGRATION_INTERRUPTED".to_string()); + stored.error_message = Some(migration_safe_message("MIGRATION_INTERRUPTED", "")); + } let current_fingerprint = self.migration_source_fingerprint().await?; let cached_scan: Option<(i64, i64, i64, i64, i64, i64, i64)> = if stored.source_fingerprint.as_deref() == Some(current_fingerprint.as_str()) { @@ -1581,6 +1633,7 @@ impl Storage { }; // This probe is deliberately read-only. It must not create a keyring // entry, key file, or change permissions while displaying status. + let key_files_before = self.key_file_digests(); let key_probe = self.resolve_secret_key(false); let mut key_provider_available = key_probe.is_ok(); let database_plaintext_count = (plaintext + ai + tunnels).max(0) as usize; @@ -1593,7 +1646,7 @@ impl Storage { && !matches!(self.secret_key_policy, SecretKeyPolicy::ExternalOnly) && encrypted == 0 && (database_plaintext_count > 0 || sync_credentials > 0 || files.iter().any(|file| file.exists)); - let mut key_error_code = key_probe.as_ref().err().cloned(); + let mut key_error_code = key_probe.as_ref().err().map(|error| migration_error_code(error).to_string()); if let Ok(resolved) = key_probe.as_ref() { if encrypted > 0 && self.validate_existing_encrypted_data(resolved.codec).await.is_err() { key_provider_available = false; @@ -1619,6 +1672,8 @@ impl Storage { "SECRET_KEY_INVALID" | "SECRET_KEY_MISMATCH" | "KEY_FILE_UNAVAILABLE" + | "KEYRING_ACCESS_FAILED" + | "KEYRING_WRITE_FAILED" | "MISSING_EXTERNAL_KEY" | "ENCRYPTED_DATA_KEY_MISSING" ) @@ -1635,7 +1690,9 @@ impl Storage { None => MigrationKeyStatus::Unavailable, }; let source_changed = stored.source_fingerprint.as_deref().is_some_and(|value| value != current_fingerprint); - let state = if fatal_key_error + let state = if matches!(stored.state, MigrationState::Failed | MigrationState::Running) { + stored.state.clone() + } else if fatal_key_error || missing_required_key || missing_existing_key || (has_legacy_data @@ -1661,10 +1718,16 @@ impl Storage { "SECRET_KEY_INVALID" => "The configured secret key is invalid", "SECRET_KEY_MISMATCH" => "The configured secret key cannot decrypt existing data", "KEY_FILE_UNAVAILABLE" => "The configured secret key file is unavailable", + "KEYRING_ACCESS_FAILED" => "The platform credential store refused access to the DBX secret-store key", + "KEYRING_WRITE_FAILED" => "DBX could not save the secret-store key in the platform credential store", "MISSING_EXTERNAL_KEY" => "An external secret key is required", _ => "The local secret provider is unavailable", }; (Some(code), Some(message.to_string())) + } else if stored.state == MigrationState::Failed && stored.error_code.is_some() { + let code = migration_error_code(stored.error_code.as_deref().unwrap()).to_string(); + let message = migration_safe_message(&code, ""); + (Some(code), Some(message)) } else if missing_required_key { (Some("MISSING_EXTERNAL_KEY".to_string()), Some("An external secret key is required".to_string())) } else if missing_existing_key { @@ -1680,6 +1743,14 @@ impl Storage { .map(|resolved| resolved.source.as_str()) .unwrap_or(SecretKeySource::Unavailable.as_str()) .to_string(); + // Reuse a successful read during the subsequent migration start. This + // keeps the read-only preflight and the first migration write from + // prompting the platform credential store twice in one action. + if key_provider_available { + if let Ok(resolved) = key_probe.as_ref() { + self.cache_secret_codec_if_unchanged(resolved.codec, key_files_before); + } + } let preflight = MigrationPreflight { migration_id: SECRET_STORE_MIGRATION_ID.to_string(), state, @@ -1730,43 +1801,77 @@ impl Storage { .await } - pub async fn start_data_migration(&self) -> Result { - let lock = DATA_MIGRATION_LOCK.get_or_init(|| tokio::sync::Mutex::new(())).lock().await; - // Migration may create or replace key material, so the codec resolved - // for earlier reads must not be reused here. - self.invalidate_secret_codec(); - let preflight = self.inspect_data_migration().await?; - if preflight.is_ready() { - return Ok(MigrationReport { - migration_id: SECRET_STORE_MIGRATION_ID.to_string(), - state: preflight.state, - backup_path: preflight.backup_path, - database_plaintext_count: 0, - legacy_json_files: Vec::new(), - verified_secret_count: 0, - error_code: None, - error_message: None, - }); + fn migration_is_active(&self) -> Result { + let file = + match std::fs::OpenOptions::new().read(true).write(true).open(self.data_dir().join(MIGRATION_LOCK_FILE)) { + Ok(file) => file, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false), + Err(_) => return Err("MIGRATION_LOCK_UNAVAILABLE".to_string()), + }; + match fs2::FileExt::try_lock_exclusive(&file) { + Ok(()) => Ok(false), // Closing the handle releases the probe lock. + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => Ok(true), + Err(_) => Err("MIGRATION_LOCK_UNAVAILABLE".to_string()), } - if !preflight.key_provider_available && !preflight.key_creation_allowed { - let code = preflight.error_code.as_deref().unwrap_or("KEY_PROVIDER_UNAVAILABLE"); - let error = code.to_string(); - self.set_migration_state(MigrationState::Failed, None, Some(code), Some(&error), None).await?; - return Err(error); + } + + fn lock_data_migration(&self) -> Result { + let mut options = std::fs::OpenOptions::new(); + options.read(true).write(true).create(true).truncate(false); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); } - self.set_migration_state(MigrationState::Running, None, None, None, Some(&migration_counts_json(&preflight))) - .await?; - let backup_path = match self.create_migration_backup().await { - Ok(path) => path, - Err(error) => { - let _ = self - .set_migration_state(MigrationState::Failed, None, Some("BACKUP_FAILED"), Some(&error), None) - .await; - return Err(error); + let file = options + .open(self.data_dir().join(MIGRATION_LOCK_FILE)) + .map_err(|_| "MIGRATION_LOCK_UNAVAILABLE".to_string())?; + fs2::FileExt::try_lock_exclusive(&file).map_err(|error| { + if error.kind() == std::io::ErrorKind::WouldBlock { + "MIGRATION_IN_PROGRESS".to_string() + } else { + "MIGRATION_LOCK_UNAVAILABLE".to_string() } - }; - self.set_migration_state(MigrationState::Running, Some(&backup_path), None, None, None).await?; + })?; + Ok(file) + } + + pub async fn start_data_migration(&self) -> Result { + let _lock = DATA_MIGRATION_LOCK.get_or_init(|| tokio::sync::Mutex::new(())).lock().await; + let _file_lock = self.lock_data_migration()?; + *self.migration_failure.lock().unwrap_or_else(|p| p.into_inner()) = None; + self.invalidate_secret_codec(); + let mut backup_path: Option = None; + let mut data_started = false; let result = async { + let preflight = self.inspect_data_migration().await?; + if preflight.is_ready() { + return Ok(MigrationReport { + migration_id: SECRET_STORE_MIGRATION_ID.to_string(), + state: preflight.state, + backup_path: preflight.backup_path, + database_plaintext_count: 0, + legacy_json_files: Vec::new(), + verified_secret_count: 0, + error_code: None, + error_message: None, + }); + } + if !preflight.key_provider_available && !preflight.key_creation_allowed { + return Err(preflight.error_code.unwrap_or_else(|| "KEY_PROVIDER_UNAVAILABLE".to_string())); + } + self.set_migration_state( + MigrationState::Running, + None, + None, + None, + Some(&migration_counts_json(&preflight)), + ) + .await?; + backup_path = Some(self.create_migration_backup().await.map_err(|_| "BACKUP_FAILED".to_string())?); + let backup_path = backup_path.as_deref().unwrap(); + self.set_migration_state(MigrationState::Running, Some(backup_path), None, None, None).await?; + data_started = true; let codec = self.secret_codec(preflight.key_creation_allowed)?; self.run_database_legacy_migrations(&codec).await?; self.migrate_from_json_staged(self.data_dir()).await?; @@ -1774,7 +1879,7 @@ impl Storage { let renamed = self.finalize_legacy_json_files().await?; self.set_migration_state( MigrationState::Succeeded, - Some(&backup_path), + Some(backup_path), None, None, Some(&{ @@ -1796,7 +1901,7 @@ impl Storage { Ok::(MigrationReport { migration_id: SECRET_STORE_MIGRATION_ID.to_string(), state: MigrationState::Succeeded, - backup_path: Some(backup_path.clone()), + backup_path: Some(backup_path.to_string()), database_plaintext_count: preflight.database_plaintext_count, legacy_json_files: renamed, verified_secret_count: verified, @@ -1805,24 +1910,37 @@ impl Storage { }) } .await; - if let Err(error) = &result { - // Every database migration helper uses its own transaction. Restore - // the pre-migration SQLite snapshot if a later JSON parse, write, - // or verification step fails, so the live database is never left - // half-upgraded. - let _ = self.restore_database_backup(&backup_path).await; - let _ = self - .set_migration_state( - MigrationState::Failed, - Some(&backup_path), - Some(migration_error_code(error)), - Some(error), - None, - ) - .await; + match result { + Ok(report) => Ok(report), + Err(error) => { + self.invalidate_secret_codec(); + let mut code = migration_error_code(&error).to_string(); + if data_started { + if let Some(path) = backup_path.as_deref() { + if self.restore_database_backup(path).await.is_err() { + code = "MIGRATION_RESTORE_FAILED".to_string(); + } + } + } + if self + .set_migration_state(MigrationState::Failed, backup_path.as_deref(), Some(&code), Some(&code), None) + .await + .is_err() + { + code = "MIGRATION_STATE_WRITE_FAILED".to_string(); + // A read-only status request must still report the failed + // action if SQLite cannot persist it. After process exit, + // a retained running record is detected via the file lock. + *self.migration_failure.lock().unwrap_or_else(|p| p.into_inner()) = + Some(MigrationFailure { code: code.clone(), backup_path }); + } + if code == "MIGRATION_STATE_WRITE_FAILED" || code == "MIGRATION_RESTORE_FAILED" { + Err(code) + } else { + Err(error) + } + } } - drop(lock); - result } pub async fn retry_data_migration(&self) -> Result { @@ -1994,7 +2112,8 @@ impl Storage { } let counts_json = counts.to_string(); let backup_path = backup_path.or(previous.backup_path); - let source_fingerprint = Some(self.migration_source_fingerprint().await?); + let source_fingerprint = + if state == "failed" { None } else { Some(self.migration_source_fingerprint().await?) }; self.with_conn(move |conn| { conn.execute( "INSERT INTO data_migrations (migration_id,state,source_fingerprint,counts_json,backup_path,error_code,error_message,started_at,completed_at) @@ -9176,7 +9295,8 @@ mod tests { .unwrap() .with_secret_key_policy(SecretKeyPolicy::ManagedDataDir); let status = reopened.inspect_data_migration().await.unwrap(); - assert_eq!(status.state, super::MigrationState::Running); + assert_eq!(status.state, super::MigrationState::Failed); + assert_eq!(status.error_code.as_deref(), Some("MIGRATION_INTERRUPTED")); assert!(!status.is_ready()); reopened.retry_data_migration().await.unwrap(); assert!(reopened.inspect_data_migration().await.unwrap().is_ready()); @@ -13836,6 +13956,16 @@ mod tests { assert_eq!(super::migration_backup_paths(&valid).unwrap(), vec!["/tmp/dbx-secret-migration-a"]); } + #[test] + fn migration_errors_preserve_keyring_failure_classification() { + assert_eq!(super::migration_error_code("KEYRING_ACCESS_FAILED: item denied"), "KEYRING_ACCESS_FAILED"); + assert_eq!(super::migration_error_code("KEYRING_WRITE_FAILED: item denied"), "KEYRING_WRITE_FAILED"); + assert_eq!( + super::migration_safe_message("KEYRING_ACCESS_FAILED", "ignored"), + "The platform credential store refused access to the DBX secret-store key" + ); + } + #[tokio::test] async fn stored_connection_count_reads_the_table_without_loading_secrets() { let dir = tempfile::tempdir().unwrap();