From 2f56011b31621dae188eb49e38bf6adeb7ef76c8 Mon Sep 17 00:00:00 2001 From: Nardo021 Date: Tue, 3 Nov 2026 12:11:21 +1100 Subject: [PATCH 1/2] fix: recover a damaged profile collection from an explicit backup Plain reset could not load a corrupt config-profiles file, while the UI told users to reset or repair it. Co-authored-by: Cursor --- docs/architecture.md | 4 +- docs/command-line.md | 5 +- docs/command-line.zh-CN.md | 2 +- docs/configuration.md | 64 +++- src/config.rs | 671 +++++++++++++++++++++++++++++++++++-- src/main.rs | 101 +++++- src/ui.rs | 32 +- src/ui/geometry_view.rs | 4 +- tests/cli_contract.rs | 251 ++++++++++++++ 9 files changed, 1074 insertions(+), 60 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index b250041..61a8822 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -94,7 +94,9 @@ User configuration is stored as at most three named profiles in and per-profile revisions are committed atomically under a cross-process lock. On first use, the existing `config-v2.json` is preserved and imported as the `default` profile. The tray supports revision-checked live reloads without -changing a mapping that is already running. See +changing a mapping that is already running. A damaged profile collection is +left unchanged by ordinary profile commands. `sbms config reset --all --backup` +backs up the original bytes and rebuilds the entire collection. See [configuration.md](configuration.md) for the storage, CLI, JSON and Rust API contracts. diff --git a/docs/command-line.md b/docs/command-line.md index 569e407..5c9361f 100644 --- a/docs/command-line.md +++ b/docs/command-line.md @@ -20,4 +20,7 @@ sbms shutdown foreground session cleanly. A mapping plan can contain up to sixteen mirror and stream-only groups. Up to three persistent configuration profiles can coexist; see [Configuration profiles](configuration.md) for import, export, -activation and hot-reload interfaces. +activation and hot-reload interfaces. `sbms config reset` resets only the +active profile in a valid collection. `sbms config reset --all --backup` +backs up the raw profile file and rebuilds the entire collection; both flags +are required. diff --git a/docs/command-line.zh-CN.md b/docs/command-line.zh-CN.md index e41c0c2..71f2480 100644 --- a/docs/command-line.zh-CN.md +++ b/docs/command-line.zh-CN.md @@ -18,4 +18,4 @@ sbms shutdown `sbms list` 会列出 `--target` 所需的稳定显示器 ID。前台运行 `map` 时按 Enter,可以正常停止并完成恢复。映射计划最多可混合十六组本地镜像和纯串流 虚拟桌面。最多可以同时保存三套配置;导入、导出、激活和热加载接口见 -[配置档案接口](configuration.md)。 +[配置档案接口](configuration.md)。`sbms config reset` 只重置一份有效配置集合里的当前档案。`sbms config reset --all --backup` 会按原始字节备份整个配置集合,然后重建为默认集合;两个参数必须同时给出。该命令会丢弃全部档案和全局偏好,不会删除显示器覆盖、日志、串流凭据或旧版迁移文件。 diff --git a/docs/configuration.md b/docs/configuration.md index 6f2e176..cb49f61 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -34,6 +34,7 @@ sbms config reload sbms config set-target sbms config clear-target sbms config reset +sbms config reset --all --backup ``` - `path` prints the profile-store path. @@ -53,12 +54,61 @@ sbms config reset - `activate` atomically changes the active profile and requests a live reload. - `delete` rejects the active profile and unknown profiles. - `reload` requests that the running tray reload the already-active profile. -- `set-target`, `clear-target` and `reset` update only the active profile and - request a live reload. +- `set-target` and `clear-target` update only the active profile and request + a live reload. +- `reset` with no other arguments resets only the active profile inside a + valid collection. Other profiles and the global preferences + `launch_intro_disabled` and `auto_map_on_login` stay unchanged. A missing + profile store is created from the normal default. If the store is damaged, + unreadable, or uses a newer schema version, `reset` fails and does not write. +- `reset --all --backup` rebuilds the entire profile collection. Both flags are + required, in either order. Any other argument combination prints usage and + exits without writing. A successful configuration commit is not rolled back when the tray is not running. CLI output reports `reload=not-running`; the configuration is loaded -on the next tray or mapping start. +on the next tray or mapping start. After `reset --all --backup` commits, +`reload=failed` means the new collection is already on disk and only the tray +notification failed. + +## Damaged profile collection + +Ordinary profile commands, including `sbms config reset`, load the collection +before changing it. A truncated file, invalid JSON, or a version 1 collection +that fails semantic validation therefore cannot be repaired by `reset`. + +`sbms config reset --all --backup` is the explicit recovery command. Under the +existing cross-process profile lock it: + +1. Reads the current `config-profiles-v1.json` bytes. +2. Writes those exact bytes to a new file in the same directory: + `config-profiles-v1.json.recovery--.bak`. + The file is created with `create_new` and flushed before the store is + replaced, so a later recovery cannot overwrite an earlier backup. +3. Atomically replaces the store with one `default` profile at revision 1 and + default global preferences. + +The command discards every saved profile and both global preferences. It does +not delete display overrides, logs, stream credentials, `config-v2.json`, or +`config-v1.json`. + +A numeric `version` greater than 1 is a newer schema. Recovery refuses it and +leaves the file unchanged, without writing a backup. A non-numeric `version`, +truncated JSON, or any other file whose schema version cannot be recognized is +damaged. Only this command can rebuild it. The command also accepts a valid +collection: it still backs up the raw bytes and replaces the whole collection. +Permission errors and other read/write failures are not treated as damage: the +source file stays in place. If the backup itself fails, nothing is replaced. +If the backup succeeds and the atomic replacement fails, the command reports +that recovery was not committed and leaves the backup in place. + +```text +sbms config reset --all --backup +``` + +```text +recovered=default revision=1 backup=%LOCALAPPDATA%\SBMS\config-profiles-v1.json.recovery--.bak reload=not-running +``` ## JSON exchange format @@ -141,8 +191,12 @@ The public API is exported from `sbms::config`: - `ConfigProfileStore::default_store()` locates the collection. - `list`, `load_active` and `load_profile` return validated persistent state. -- `save_profile`, `save_active_as`, `activate`, `delete` and `update_active` - perform locked atomic transactions. +- `save_profile`, `save_active_as`, `activate`, `delete`, `update_active` and + `reset_active` perform locked atomic transactions. +- `recover_with_backup` is the locked recovery used by + `sbms config reset --all --backup`. It returns the new snapshot and the + backup path. `ConfigError::allows_profile_collection_recovery` is true only + for a damaged collection this build can rebuild. - `save_active_if_revision` is the compare-and-swap save operation for a pinned UI session. - `ConfigStore::load_strict` validates standalone import files; `save` writes diff --git a/src/config.rs b/src/config.rs index a2059e5..31dd9d6 100644 --- a/src/config.rs +++ b/src/config.rs @@ -28,6 +28,7 @@ use crate::limits::{ const CONFIG_VERSION: u32 = 2; const LEGACY_CONFIG_VERSION: u32 = 1; const CONFIG_PROFILES_VERSION: u32 = 1; +pub const RECOVER_PROFILE_COLLECTION_COMMAND: &str = "sbms config reset --all --backup"; pub const MAX_CONFIG_PROFILES: usize = 3; const DISPLAY_OVERRIDES_VERSION: u32 = 1; const CONFIG_DIRECTORY: &str = "SBMS"; @@ -217,6 +218,12 @@ pub struct ProfileDeleteOutcome { pub active_changed: bool, } +#[derive(Clone, Debug, PartialEq)] +pub struct ProfileRecovery { + pub snapshot: ProfileSnapshot, + pub backup_path: PathBuf, +} + #[derive(Clone, Debug)] pub struct ConfigProfileStore { path: PathBuf, @@ -292,6 +299,10 @@ impl ConfigError { pub fn new(message: impl Into) -> Self { Self(message.into()) } + + pub fn allows_profile_collection_recovery(&self) -> bool { + self.0.contains("is a damaged SBMS config profile store:") + } } impl Display for ConfigError { @@ -1283,17 +1294,7 @@ impl ConfigProfileStore { let mut profiles = if self.path.exists() { self.load_or_initialize_locked()? } else { - ConfigProfiles { - version: CONFIG_PROFILES_VERSION, - active_profile: "default".into(), - launch_intro_disabled: false, - auto_map_on_login: false, - profiles: vec![ConfigProfile { - id: "default".into(), - revision: 1, - config: AppConfig::default(), - }], - } + default_config_profiles() }; let active_id = profiles.active_profile.clone(); let profile = profiles @@ -1306,19 +1307,46 @@ impl ConfigProfileStore { Ok(result) } + pub fn recover_with_backup(&self) -> Result { + let _guard = CrossProcessConfigGuard::acquire()?; + let bytes = match fs::read(&self.path) { + Ok(bytes) => bytes, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + return Err(ConfigError(format!( + "config profile store {} does not exist and was not created", + self.path.display() + ))); + } + Err(error) => { + return Err(ConfigError(format!( + "could not read {}: {error}", + self.path.display() + ))); + } + }; + if let Some(version) = recognized_future_profiles_version(&bytes) { + return Err(future_profile_store(&self.path, &version)); + } + // Flush the original bytes before replacing the store. A backup error + // returns while the source file is still untouched. + let backup = write_unique_profile_backup(&self.path, &bytes)?; + let profiles = default_config_profiles(); + if let Err(error) = self.save_locked(&profiles) { + return Err(ConfigError(format!( + "config profile recovery was not committed; {}; backup remains at {}: {error}", + profile_store_after_failed_replace(&self.path, &bytes), + backup.display() + ))); + } + Ok(ProfileRecovery { + snapshot: snapshot(profiles.active()), + backup_path: backup, + }) + } + fn load_or_initialize_locked(&self) -> Result { match fs::read(&self.path) { - Ok(bytes) => { - let profiles = - serde_json::from_slice::(&bytes).map_err(|error| { - ConfigError(format!( - "{} is not a valid SBMS config profile store: {error}", - self.path.display() - )) - })?; - profiles.validate()?; - Ok(profiles) - } + Ok(bytes) => parse_profile_store(&self.path, &bytes), Err(error) if error.kind() == std::io::ErrorKind::NotFound => { let legacy_store = ConfigStore { path: self.legacy_config_path.clone(), @@ -1340,17 +1368,7 @@ impl ConfigProfileStore { } Err(error) => return Err(error), }; - let profiles = ConfigProfiles { - version: CONFIG_PROFILES_VERSION, - active_profile: "default".into(), - launch_intro_disabled: false, - auto_map_on_login: false, - profiles: vec![ConfigProfile { - id: "default".into(), - revision: 1, - config, - }], - }; + let profiles = single_profile_collection(config); self.save_locked(&profiles)?; Ok(profiles) } @@ -1403,6 +1421,206 @@ impl Drop for CrossProcessConfigGuard { } } +#[cfg(test)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ProfileStoreTestFault { + Backup, + Replace, +} + +#[cfg(test)] +thread_local! { + static PROFILE_STORE_TEST_FAULT: std::cell::Cell> = + const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +#[must_use] +struct ProfileStoreTestFaultGuard; + +#[cfg(test)] +impl Drop for ProfileStoreTestFaultGuard { + fn drop(&mut self) { + PROFILE_STORE_TEST_FAULT.with(|fault| fault.set(None)); + } +} + +#[cfg(test)] +fn inject_profile_store_fault(fault: ProfileStoreTestFault) -> ProfileStoreTestFaultGuard { + PROFILE_STORE_TEST_FAULT.with(|slot| slot.set(Some(fault))); + ProfileStoreTestFaultGuard +} + +#[cfg(test)] +fn consume_profile_store_test_fault(expected: ProfileStoreTestFault) -> bool { + PROFILE_STORE_TEST_FAULT.with(|slot| { + if slot.get() == Some(expected) { + slot.set(None); + true + } else { + false + } + }) +} + +fn single_profile_collection(config: AppConfig) -> ConfigProfiles { + ConfigProfiles { + version: CONFIG_PROFILES_VERSION, + active_profile: "default".into(), + launch_intro_disabled: false, + auto_map_on_login: false, + profiles: vec![ConfigProfile { + id: "default".into(), + revision: 1, + config, + }], + } +} + +fn default_config_profiles() -> ConfigProfiles { + single_profile_collection(AppConfig::default()) +} + +fn damaged_profile_store(path: &Path, detail: impl Display) -> ConfigError { + let path = path.display(); + ConfigError(format!( + "{path} is a damaged SBMS config profile store: {detail}. Run `{RECOVER_PROFILE_COLLECTION_COMMAND}` to back up and rebuild the entire profile collection" + )) +} + +fn future_profile_store(path: &Path, version: &str) -> ConfigError { + let path = path.display(); + ConfigError(format!( + "{path} uses config profiles version {version}, which is newer than this SBMS and was left unchanged" + )) +} + +fn recognized_future_profiles_version(bytes: &[u8]) -> Option { + let mut deserializer = serde_json::Deserializer::from_slice(bytes); + let value = serde_json::Value::deserialize(&mut deserializer).ok()?; + let version = value.as_object()?.get("version")?.as_number()?; + if let Some(integer) = version.as_u64() { + return (integer > u64::from(CONFIG_PROFILES_VERSION)).then(|| integer.to_string()); + } + if version.as_i64().is_some() { + return None; + } + let float = version.as_f64()?; + (float.is_finite() && float > f64::from(CONFIG_PROFILES_VERSION)).then(|| version.to_string()) +} + +fn parse_profile_store(path: &Path, bytes: &[u8]) -> Result { + if let Some(version) = recognized_future_profiles_version(bytes) { + return Err(future_profile_store(path, &version)); + } + let profiles = serde_json::from_slice::(bytes) + .map_err(|error| damaged_profile_store(path, error))?; + profiles + .validate() + .map_err(|error| damaged_profile_store(path, error))?; + Ok(profiles) +} + +fn profile_store_after_failed_replace(path: &Path, original: &[u8]) -> String { + match fs::read(path) { + Ok(current) if current == original => { + format!("original file {} is unchanged", path.display()) + } + Ok(_) => format!( + "original file {} no longer matches the backed-up bytes", + path.display() + ), + Err(error) => format!( + "original file {} could not be read after the failed replacement: {error}", + path.display() + ), + } +} + +fn backup_parent(source: &Path) -> Result<&Path, ConfigError> { + match source.parent() { + Some(parent) if !parent.as_os_str().is_empty() => Ok(parent), + Some(_) => Ok(Path::new(".")), + None => Err(ConfigError(format!( + "config profile backup path has no parent directory: {}", + source.display() + ))), + } +} + +fn write_backup_file(file: &mut File, bytes: &[u8]) -> std::io::Result<()> { + file.write_all(bytes)?; + file.sync_all() +} + +fn write_unique_profile_backup(source: &Path, bytes: &[u8]) -> Result { + #[cfg(test)] + if consume_profile_store_test_fault(ProfileStoreTestFault::Backup) { + return Err(ConfigError( + "could not create config profile backup: injected failure".into(), + )); + } + + let parent = backup_parent(source)?; + let file_name = source + .file_name() + .and_then(OsStr::to_str) + .unwrap_or(CONFIG_PROFILES_FILE); + let mut collision = None; + for _ in 0..128 { + let sequence = TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed); + let path = parent.join(format!( + "{file_name}.recovery-{}-{sequence}.bak", + std::process::id() + )); + match OpenOptions::new().write(true).create_new(true).open(&path) { + Ok(mut file) => { + if let Err(error) = write_backup_file(&mut file, bytes) { + drop(file); + let _ = fs::remove_file(&path); + return Err(ConfigError(format!( + "could not write config profile backup {}: {error}", + path.display() + ))); + } + drop(file); + match fs::read(&path) { + Ok(stored) if stored == bytes => return Ok(path), + Ok(_) => { + let _ = fs::remove_file(&path); + return Err(ConfigError(format!( + "config profile backup {} did not retain the original bytes", + path.display() + ))); + } + Err(error) => { + let _ = fs::remove_file(&path); + return Err(ConfigError(format!( + "could not read config profile backup {}: {error}", + path.display() + ))); + } + } + } + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + collision = Some(error); + } + Err(error) => { + return Err(ConfigError(format!( + "could not create config profile backup {}: {error}", + path.display() + ))); + } + } + } + Err(ConfigError(format!( + "could not allocate a unique config profile backup: {}", + collision + .map(|error| error.to_string()) + .unwrap_or_else(|| "too many attempts".into()) + ))) +} + fn snapshot(profile: &ConfigProfile) -> ProfileSnapshot { ProfileSnapshot { profile: ProfileRevision { @@ -1615,6 +1833,13 @@ fn create_temporary(parent: &Path, destination: &Path) -> Result<(PathBuf, File) } fn atomic_replace(temporary: &Path, destination: &Path) -> Result<(), ConfigError> { + #[cfg(test)] + if consume_profile_store_test_fault(ProfileStoreTestFault::Replace) { + return Err(ConfigError(format!( + "could not atomically replace {}: injected failure", + destination.display() + ))); + } let temporary_wide = wide(temporary.as_os_str()); let destination_wide = wide(destination.as_os_str()); let temporary_pcwstr = PCWSTR(temporary_wide.as_ptr()); @@ -2340,4 +2565,384 @@ mod tests { assert_eq!(profiles.load_active().unwrap(), updated); fs::remove_dir_all(root).unwrap(); } + + fn write_unrelated_files(root: &Path) -> Vec<(PathBuf, &'static [u8])> { + let files = [ + ( + DISPLAY_OVERRIDES_FILE, + br#"{"version":1,"displays":[]}"#.as_slice(), + ), + (CONFIG_FILE, br#"{"version":2,"groups":[]}"#), + (LEGACY_CONFIG_FILE, b"{legacy source"), + ("sbms.log", b"log-bytes"), + ("credentials.json", b"stream-secret"), + ]; + files + .into_iter() + .map(|(name, bytes)| { + let path = root.join(name); + fs::write(&path, bytes).unwrap(); + (path, bytes) + }) + .collect() + } + + fn assert_unrelated_unchanged(files: &[(PathBuf, &'static [u8])]) { + for (path, bytes) in files { + assert_eq!(fs::read(path).unwrap(), *bytes, "{}", path.display()); + } + } + + fn recovery_backups(root: &Path) -> Vec { + let mut paths: Vec<_> = fs::read_dir(root) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| { + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.contains(".recovery-") && name.ends_with(".bak")) + }) + .collect(); + paths.sort(); + paths + } + + fn temporary_profile_files(root: &Path) -> Vec { + fs::read_dir(root) + .unwrap() + .filter_map(|entry| { + let path = entry.ok()?.path(); + let name = path.file_name()?.to_str()?; + name.contains(".tmp").then_some(path) + }) + .collect() + } + + fn prepare_profile_bytes(name: &str, bytes: &[u8]) -> (PathBuf, ConfigProfileStore) { + let (root, store) = test_profile_store(name); + fs::create_dir_all(&root).unwrap(); + fs::write(store.path(), bytes).unwrap(); + (root, store) + } + + #[test] + fn explicit_recovery_restores_unreadable_profile_bytes_and_keeps_neighbors() { + let cases: &[(&str, &[u8])] = &[ + ("truncated", b"{not json"), + ("cut-off", br#"{"version":1,"profiles":["#), + ("non-utf8", b"\xff\xfe{not json"), + ("string-version", br#"{"version":"99","profiles":[]}"#), + ("incomplete-future", br#"{"version":99"#), + ]; + for (name, original) in cases { + let (root, store) = prepare_profile_bytes(name, original); + let unrelated = write_unrelated_files(&root); + let plain_reset = store.reset_active().unwrap_err(); + assert!( + plain_reset.allows_profile_collection_recovery(), + "{name}: {plain_reset}" + ); + assert!( + !plain_reset.to_string().contains("was not committed"), + "{name}" + ); + assert_eq!(fs::read(store.path()).unwrap(), *original, "{name}"); + assert!(recovery_backups(&root).is_empty(), "{name}"); + + let recovered = store.recover_with_backup().unwrap(); + assert_eq!( + fs::read(&recovered.backup_path).unwrap(), + *original, + "{name}" + ); + assert_eq!(recovered.snapshot.profile.id, "default"); + assert_eq!(recovered.snapshot.profile.revision, 1); + assert_eq!(recovered.snapshot.config, AppConfig::default()); + assert_ne!(fs::read(store.path()).unwrap(), *original, "{name}"); + let loaded = store.load_active().unwrap(); + assert_eq!(loaded, recovered.snapshot); + assert_unrelated_unchanged(&unrelated); + + let updated = store + .update_active(|config| { + *config = config_with_target("recovered-target"); + Ok(()) + }) + .unwrap(); + assert_eq!(updated.profile.revision, 2); + assert_eq!(store.load_active().unwrap(), updated); + let (saved, active) = store + .save_profile("edited", &config_with_target("edited-target"), false, false) + .unwrap(); + assert!(!active); + assert_eq!(saved.profile.id, "edited"); + assert_eq!(store.list().unwrap().profiles.len(), 2); + assert_eq!( + store.load_active().unwrap().config, + config_with_target("recovered-target") + ); + assert_eq!( + fs::read(&recovered.backup_path).unwrap(), + *original, + "{name}" + ); + assert_unrelated_unchanged(&unrelated); + fs::remove_dir_all(root).unwrap(); + } + } + + #[test] + fn explicit_recovery_rebuilds_a_known_but_semantically_invalid_collection() { + let original = br#"{"version":1,"active_profile":"missing","launch_intro_disabled":true,"auto_map_on_login":true,"profiles":[{"id":"default","revision":3,"config":{"version":2,"groups":[{"id":0,"route":{"kind":"mirror","target_id":"office"}}],"selected_group_id":0}},{"id":"gaming","revision":4,"config":{"version":2,"groups":[{"id":0,"route":{"kind":"mirror","target_id":"gaming"}}],"selected_group_id":0}}]}"#; + let (root, store) = prepare_profile_bytes("semantic", original); + let unrelated = write_unrelated_files(&root); + let error = store.load_active().unwrap_err(); + assert!(error.allows_profile_collection_recovery(), "{error}"); + assert!(error.to_string().contains("does not exist"), "{error}"); + + let recovered = store.recover_with_backup().unwrap(); + assert_eq!(fs::read(&recovered.backup_path).unwrap(), original); + let profiles = store.list().unwrap(); + assert_eq!(profiles.profiles.len(), 1); + assert_eq!(profiles.active_profile, "default"); + assert!(!profiles.launch_intro_disabled); + assert!(!profiles.auto_map_on_login); + assert_eq!(profiles.active().config, AppConfig::default()); + assert_eq!(profiles.active().revision, 1); + assert_unrelated_unchanged(&unrelated); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn explicit_recovery_backs_up_raw_bytes_and_repeated_runs_keep_every_backup() { + let (root, store) = test_profile_store("repeat"); + store.load_active().unwrap(); + store.set_launch_intro_disabled(true).unwrap(); + store.set_auto_map_on_login(true).unwrap(); + store + .save_profile("gaming", &config_with_target("gaming-display"), false, true) + .unwrap(); + let original = fs::read(store.path()).unwrap(); + let first = store.recover_with_backup().unwrap(); + assert_eq!(fs::read(&first.backup_path).unwrap(), original); + let rebuilt = fs::read(store.path()).unwrap(); + assert_ne!(rebuilt, original); + let profiles = store.list().unwrap(); + assert_eq!(profiles.profiles.len(), 1); + assert!(!profiles.launch_intro_disabled); + assert!(!profiles.auto_map_on_login); + + let second = store.recover_with_backup().unwrap(); + assert_ne!(first.backup_path, second.backup_path); + assert_eq!(fs::read(&first.backup_path).unwrap(), original); + assert_eq!(fs::read(&second.backup_path).unwrap(), rebuilt); + assert_eq!(recovery_backups(&root).len(), 2); + assert_eq!(store.load_active().unwrap().profile.revision, 1); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn profile_backup_creation_fails_when_the_parent_is_not_a_directory() { + let parent = env::temp_dir().join(format!( + "sbms-config-backup-parent-{}-{}", + std::process::id(), + TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + fs::write(&parent, b"not-a-directory").unwrap(); + let source = parent.join(CONFIG_PROFILES_FILE); + let error = write_unique_profile_backup(&source, b"raw-bytes").unwrap_err(); + assert!( + error + .to_string() + .contains("could not create config profile backup"), + "{error}" + ); + assert_eq!(fs::read(&parent).unwrap(), b"not-a-directory"); + assert!(!source.exists()); + fs::remove_file(parent).unwrap(); + } + + #[test] + fn profile_recovery_keeps_the_source_when_backup_fails() { + let original = b"{not-json"; + let (root, store) = prepare_profile_bytes("backup-fails", original); + let unrelated = write_unrelated_files(&root); + // The transaction holds the profile lock across backup and replacement, + // so an external process cannot fail only the backup step. This fault + // stands in for that IO error before any backup file is created. + let _fault = inject_profile_store_fault(ProfileStoreTestFault::Backup); + let error = store.recover_with_backup().unwrap_err(); + drop(_fault); + let message = error.to_string(); + assert!( + message.contains("could not create config profile backup"), + "{message}" + ); + assert!(!message.contains("was not committed"), "{message}"); + assert!( + !message.contains("configuration recovery was committed"), + "{message}" + ); + assert!(!error.allows_profile_collection_recovery(), "{message}"); + assert_eq!(fs::read(store.path()).unwrap(), original); + assert!(recovery_backups(&root).is_empty()); + assert!(temporary_profile_files(&root).is_empty()); + assert_unrelated_unchanged(&unrelated); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn profile_recovery_keeps_the_backup_when_atomic_replace_fails() { + let original = b"\xff\xfe{truncated"; + let (root, store) = prepare_profile_bytes("replace-fails", original); + let unrelated = write_unrelated_files(&root); + let _fault = inject_profile_store_fault(ProfileStoreTestFault::Replace); + let error = store.recover_with_backup().unwrap_err(); + drop(_fault); + let message = error.to_string(); + assert!(message.contains("was not committed"), "{message}"); + assert!(message.contains("is unchanged"), "{message}"); + assert!(message.contains("backup remains at"), "{message}"); + assert!( + message.contains("could not atomically replace"), + "{message}" + ); + assert!( + !message.contains("configuration recovery was committed"), + "{message}" + ); + assert_eq!(fs::read(store.path()).unwrap(), original); + let backups = recovery_backups(&root); + assert_eq!(backups.len(), 1); + assert_eq!(fs::read(&backups[0]).unwrap(), original); + let backup_name = backups[0] + .file_name() + .and_then(|name| name.to_str()) + .unwrap(); + assert!(message.contains(backup_name), "{message}"); + assert!(temporary_profile_files(&root).is_empty()); + assert_unrelated_unchanged(&unrelated); + + let recovered = store.recover_with_backup().unwrap(); + assert_ne!(recovered.backup_path, backups[0]); + assert_eq!(fs::read(&backups[0]).unwrap(), original); + assert_eq!(fs::read(&recovered.backup_path).unwrap(), original); + assert_eq!(store.load_active().unwrap().config, AppConfig::default()); + assert_unrelated_unchanged(&unrelated); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn future_profile_schema_is_refused_without_backup_or_replacement() { + let cases: &[(&str, &[u8])] = &[ + ( + "version-99", + br#"{"version":99,"active_profile":"default","profiles":[]}"#, + ), + ("version-2-extra", br#"{"version":2,"extra":true}"#), + ("version-prefix", br#"{"version":99} trailing"#), + ("version-float", br#"{"version":1.5,"profiles":[]}"#), + ]; + for (name, original) in cases { + let (root, store) = prepare_profile_bytes(name, original); + let unrelated = write_unrelated_files(&root); + for error in [ + store.reset_active().unwrap_err(), + store.recover_with_backup().unwrap_err(), + store.load_active().unwrap_err(), + ] { + let message = error.to_string(); + assert!( + message.contains("newer than this SBMS"), + "{name}: {message}" + ); + assert!(message.contains("left unchanged"), "{name}: {message}"); + assert!( + !error.allows_profile_collection_recovery(), + "{name}: {message}" + ); + assert!( + !message.contains(RECOVER_PROFILE_COLLECTION_COMMAND), + "{name}" + ); + assert!(!message.contains("was not committed"), "{name}: {message}"); + } + assert_eq!(fs::read(store.path()).unwrap(), *original, "{name}"); + assert!(recovery_backups(&root).is_empty(), "{name}"); + assert_unrelated_unchanged(&unrelated); + fs::remove_dir_all(root).unwrap(); + } + } + + #[test] + fn profile_recovery_does_not_treat_read_errors_or_absence_as_damage() { + let (root, store) = test_profile_store("missing-store"); + let missing = store.recover_with_backup().unwrap_err(); + assert!( + missing + .to_string() + .contains("does not exist and was not created"), + "{missing}" + ); + assert!(!missing.allows_profile_collection_recovery(), "{missing}"); + assert!(!root.exists()); + + let (root, store) = test_profile_store("directory-store"); + fs::create_dir_all(store.path()).unwrap(); + let unrelated = root.join("credentials.json"); + fs::write(&unrelated, b"stream-secret").unwrap(); + let error = store.recover_with_backup().unwrap_err(); + let message = error.to_string(); + assert!(message.contains("could not read"), "{message}"); + assert!(!error.allows_profile_collection_recovery(), "{message}"); + assert!( + !message.contains(RECOVER_PROFILE_COLLECTION_COMMAND), + "{message}" + ); + assert!(store.path().is_dir()); + assert_eq!(fs::read(&unrelated).unwrap(), b"stream-secret"); + assert!(recovery_backups(&root).is_empty()); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn reset_active_resets_only_the_active_profile_inside_a_valid_collection() { + let (root, store) = test_profile_store("reset-active-only"); + let unrelated = { + fs::create_dir_all(&root).unwrap(); + write_unrelated_files(&root) + }; + store.load_active().unwrap(); + store + .update_active(|config| { + *config = config_with_target("default-display"); + Ok(()) + }) + .unwrap(); + store.set_launch_intro_disabled(true).unwrap(); + store.set_auto_map_on_login(true).unwrap(); + store + .save_profile("gaming", &config_with_target("gaming-display"), false, true) + .unwrap(); + + let snapshot = store.reset_active().unwrap(); + assert_eq!(snapshot.profile.id, "gaming"); + assert_eq!(snapshot.config, AppConfig::default()); + let profiles = store.list().unwrap(); + assert_eq!(profiles.profiles.len(), 2); + assert_eq!(profiles.active_profile, "gaming"); + assert!(profiles.launch_intro_disabled); + assert!(profiles.auto_map_on_login); + assert_eq!( + profiles.profile("default").unwrap().config, + config_with_target("default-display") + ); + assert_eq!( + profiles.profile("gaming").unwrap().config, + AppConfig::default() + ); + assert!(recovery_backups(&root).is_empty()); + assert_unrelated_unchanged(&unrelated); + fs::remove_dir_all(root).unwrap(); + } } diff --git a/src/main.rs b/src/main.rs index 8bd4a3e..40a39c7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,7 +6,9 @@ use std::path::Path; use std::sync::Arc; use std::time::Duration; -use sbms::config::{ConfigError, ConfigProfileStore, ConfigStore, GroupRouteConfig}; +use sbms::config::{ + ConfigError, ConfigProfileStore, ConfigStore, GroupRouteConfig, ProfileRecovery, +}; use sbms::diagnostics::{self, Level, MappingSessionId}; use sbms::display::{active_displays, unique_physical_display}; use sbms::geometry::Rotation; @@ -642,15 +644,25 @@ fn config(mut arguments: impl Iterator) -> Result<(), Box { - let snapshot = store.reset_active()?; - println!( - "reset={} revision={} reload={}", - snapshot.profile.id, - snapshot.profile.revision, - reload_status(signal_config_reload()?) - ); - } + Some("reset") => match reset_args(arguments) { + ResetArgs::Active => { + let snapshot = store.reset_active()?; + println!( + "reset={} revision={} reload={}", + snapshot.profile.id, + snapshot.profile.revision, + reload_status(signal_config_reload()?) + ); + } + ResetArgs::RecoverCollection => { + let recovery = store.recover_with_backup()?; + report_profile_recovery( + &recovery, + signal_config_reload().map_err(|error| error.to_string()), + )?; + } + ResetArgs::Invalid => usage(), + }, _ => usage(), } Ok(()) @@ -660,6 +672,57 @@ fn signal_config_reload() -> Result> { sbms::control::signal_config_reload().map_err(Into::into) } +enum ResetArgs { + Active, + RecoverCollection, + Invalid, +} + +fn reset_args(arguments: impl Iterator) -> ResetArgs { + let arguments: Vec = arguments.collect(); + match arguments.as_slice() { + [] => ResetArgs::Active, + [left, right] + if (left == "--all" && right == "--backup") + || (left == "--backup" && right == "--all") => + { + ResetArgs::RecoverCollection + } + _ => ResetArgs::Invalid, + } +} + +fn report_profile_recovery( + recovery: &ProfileRecovery, + reload: Result, +) -> Result<(), Box> { + match reload { + Ok(signaled) => { + println!( + "recovered={} revision={} backup={} reload={}", + recovery.snapshot.profile.id, + recovery.snapshot.profile.revision, + recovery.backup_path.display(), + reload_status(signaled) + ); + Ok(()) + } + Err(error) => { + println!( + "recovered={} revision={} backup={} reload=failed", + recovery.snapshot.profile.id, + recovery.snapshot.profile.revision, + recovery.backup_path.display() + ); + Err(committed_recovery_reload_error(&error).into()) + } + } +} + +fn committed_recovery_reload_error(error: &str) -> String { + format!("configuration recovery was committed; tray reload failed: {error}") +} + fn reload_status(signaled: bool) -> &'static str { if signaled { "signaled" } else { "not-running" } } @@ -711,8 +774,26 @@ fn usage() -> ! { sbms config activate|delete sbms config reload sbms config set-target |clear-target|reset + sbms config reset --all --backup sbms shutdown sbms ui" ); std::process::exit(2); } + +#[cfg(test)] +mod tests { + use super::committed_recovery_reload_error; + + #[test] + fn reload_failure_reports_that_recovery_stays_committed() { + let message = committed_recovery_reload_error( + "OpenEventW(config reload) failed: Access is denied. (os error 5)", + ); + assert!(message.contains("configuration recovery was committed")); + assert!(message.contains("tray reload failed")); + assert!(message.contains("OpenEventW(config reload) failed")); + assert!(!message.contains("rolled back")); + assert!(!message.contains("was not committed")); + } +} diff --git a/src/ui.rs b/src/ui.rs index 4a8ec99..50a16d9 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -6,8 +6,9 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; use crate::config::{ - AppConfig, ConfigProfileStore, ConfigProfiles, DisplayOverrideStore, DisplayOverrides, - MAX_CONFIG_PROFILES, ProfileRevision, ReferenceSource, + AppConfig, ConfigError, ConfigProfileStore, ConfigProfiles, DisplayOverrideStore, + DisplayOverrides, MAX_CONFIG_PROFILES, ProfileRevision, RECOVER_PROFILE_COLLECTION_COMMAND, + ReferenceSource, }; use crate::control::{TrayInstance, listen_for_config_reload, listen_for_shutdown}; use crate::controller::{Controller, ControllerEvent, DisplayOption}; @@ -1460,7 +1461,8 @@ fn load_group_config(ui: &QuickAccess) -> LoadedGroups { Err(error) => { set_geometry_unconfigured(ui); ui.set_geometry_save_blocked(true); - ui.set_geometry_error(error.to_string().into()); + diagnostics::log(Level::Error, "config", "load", None, error.to_string()); + ui.set_geometry_error(profile_load_message(&error).into()); return default_loaded_groups(); } }; @@ -1512,10 +1514,11 @@ fn apply_config_reload( Ok(snapshot) => snapshot, Err(error) => { diagnostics::log(Level::Error, "config", "reload", None, error.to_string()); + let detail = profile_load_message(&error); surface_transient_error( ui, error_revision, - &format!("Couldn’t reload configuration: {error}"), + &format!("Couldn’t reload configuration: {detail}"), ); return false; } @@ -1582,10 +1585,13 @@ fn persist_groups( profile_revision: &Arc>, ) -> bool { if ui.get_geometry_save_blocked() { - surface_persistence_error( - ui, - "The saved configuration is invalid; reset or repair it before saving", - ); + let existing = ui.get_geometry_error().to_string(); + let message = if existing.is_empty() { + "The saved configuration could not be loaded and was left unchanged".to_string() + } else { + existing + }; + surface_persistence_error(ui, &message); return false; } let validated = match validate_group_drafts(groups) { @@ -1661,6 +1667,16 @@ fn finish_profile_save(ui: slint::Weak, generation: u64, succeeded: } } +fn profile_load_message(error: &ConfigError) -> String { + if error.allows_profile_collection_recovery() { + format!( + "The saved configuration is damaged. Run `{RECOVER_PROFILE_COLLECTION_COMMAND}` to back up and rebuild the entire profile collection before saving" + ) + } else { + error.to_string() + } +} + fn surface_persistence_error(ui: &QuickAccess, error: &str) { ui.set_error_text(format!("Couldn’t save mapping groups: {error}").into()); ui.set_state_detail("Mapping group changes were not saved".into()); diff --git a/src/ui/geometry_view.rs b/src/ui/geometry_view.rs index 787e5cd..059edc2 100644 --- a/src/ui/geometry_view.rs +++ b/src/ui/geometry_view.rs @@ -463,7 +463,9 @@ pub(super) fn set_geometry_result(ui: &QuickAccess, result: SizingResult, config format!("Scale {:.2}× × {:.2}×", result.scale_x, result.scale_y).into(), ); ui.set_geometry_valid(!ui.get_geometry_save_blocked()); - ui.set_geometry_error("".into()); + if !ui.get_geometry_save_blocked() { + ui.set_geometry_error("".into()); + } if configured { let refresh = result .preferred_refresh_millihz diff --git a/tests/cli_contract.rs b/tests/cli_contract.rs index 878b83b..f0e4196 100644 --- a/tests/cli_contract.rs +++ b/tests/cli_contract.rs @@ -65,6 +65,7 @@ fn usage() -> &'static str { sbms config activate|delete sbms config reload sbms config set-target |clear-target|reset + sbms config reset --all --backup sbms shutdown sbms ui " @@ -292,6 +293,256 @@ fn config_export_never_overwrites_store_or_existing_destination_without_force() assert_eq!(fs::read(destination).unwrap(), b"keep-me"); } +fn recovery_backups(root: &TestRoot) -> Vec { + let profiles = root.profiles_path(); + let directory = profiles.parent().unwrap(); + let mut paths: Vec<_> = fs::read_dir(directory) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| { + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.contains(".recovery-") && name.ends_with(".bak")) + }) + .collect(); + paths.sort(); + paths +} + +fn write_profile_neighbors(root: &TestRoot) -> (PathBuf, Vec, PathBuf, Vec) { + let profiles = root.profiles_path(); + let directory = profiles.parent().unwrap(); + fs::create_dir_all(directory).unwrap(); + let legacy = root.config_path(); + let legacy_bytes = b"legacy-source".to_vec(); + fs::write(&legacy, &legacy_bytes).unwrap(); + let overrides = directory.join("display-overrides-v1.json"); + let override_bytes = br#"{"version":1,"displays":[]}"#.to_vec(); + fs::write(&overrides, &override_bytes).unwrap(); + let credentials = directory.join("credentials.json"); + fs::write(&credentials, b"stream-secret").unwrap(); + let log = directory.join("sbms.log"); + fs::write(&log, b"log-bytes").unwrap(); + (legacy, legacy_bytes, overrides, override_bytes) +} + +#[test] +fn config_reset_rejects_incomplete_recovery_arguments_without_writing() { + let root = TestRoot::new("reset-args"); + let profiles = root.profiles_path(); + fs::create_dir_all(profiles.parent().unwrap()).unwrap(); + let original = b"{not json".to_vec(); + fs::write(&profiles, &original).unwrap(); + let (legacy, legacy_bytes, overrides, override_bytes) = write_profile_neighbors(&root); + + for arguments in [ + &["config", "reset", "--all"][..], + &["config", "reset", "--backup"][..], + &["config", "reset", "--all", "--backup", "extra"][..], + &["config", "reset", "--backup", "--all", "--force"][..], + &["config", "reset", "--all", "--all"][..], + &["config", "reset", "--backup", "--backup"][..], + ] { + let output = run(&root, arguments); + assert_eq!( + output.status.code(), + Some(2), + "{arguments:?}\n{}", + text(&output.stderr) + ); + assert_eq!(text(&output.stdout), ""); + assert_eq!(text(&output.stderr), usage()); + assert_eq!(fs::read(&profiles).unwrap(), original, "{arguments:?}"); + assert_eq!(fs::read(&legacy).unwrap(), legacy_bytes, "{arguments:?}"); + assert_eq!( + fs::read(&overrides).unwrap(), + override_bytes, + "{arguments:?}" + ); + assert_eq!( + fs::read(profiles.parent().unwrap().join("credentials.json")).unwrap(), + b"stream-secret" + ); + assert_eq!( + fs::read(profiles.parent().unwrap().join("sbms.log")).unwrap(), + b"log-bytes" + ); + assert!(recovery_backups(&root).is_empty(), "{arguments:?}"); + } +} + +#[test] +fn config_reset_all_backup_restores_damaged_bytes_and_can_save_again() { + let root = TestRoot::new("recover-store"); + let profiles = root.profiles_path(); + fs::create_dir_all(profiles.parent().unwrap()).unwrap(); + let original = b"\xff\xfe{not json".to_vec(); + fs::write(&profiles, &original).unwrap(); + let (legacy, legacy_bytes, overrides, override_bytes) = write_profile_neighbors(&root); + + let recovered = run(&root, &["config", "reset", "--backup", "--all"]); + assert!(recovered.status.success(), "{}", text(&recovered.stderr)); + let stdout = text(&recovered.stdout); + assert!(stdout.contains("recovered=default"), "{stdout}"); + assert!(stdout.contains("revision=1"), "{stdout}"); + assert!(stdout.contains("backup="), "{stdout}"); + assert!(stdout.contains("reload="), "{stdout}"); + assert!(!stdout.contains("reload=failed"), "{stdout}"); + let backups = recovery_backups(&root); + assert_eq!(backups.len(), 1); + assert_eq!(fs::read(&backups[0]).unwrap(), original); + let backup_name = backups[0] + .file_name() + .and_then(|name| name.to_str()) + .unwrap(); + assert!(stdout.contains(backup_name), "{stdout}"); + assert_eq!(fs::read(&legacy).unwrap(), legacy_bytes); + assert_eq!(fs::read(&overrides).unwrap(), override_bytes); + assert_eq!( + fs::read(profiles.parent().unwrap().join("credentials.json")).unwrap(), + b"stream-secret" + ); + assert_eq!( + fs::read(profiles.parent().unwrap().join("sbms.log")).unwrap(), + b"log-bytes" + ); + + let rebuilt = fs::read(&profiles).unwrap(); + let again = run(&root, &["config", "reset", "--all", "--backup"]); + assert!(again.status.success(), "{}", text(&again.stderr)); + let backups = recovery_backups(&root); + assert_eq!(backups.len(), 2); + let backup_bytes: Vec> = backups.iter().map(|path| fs::read(path).unwrap()).collect(); + assert!(backup_bytes.iter().any(|bytes| bytes == &original)); + assert!(backup_bytes.iter().any(|bytes| bytes == &rebuilt)); + + let shown = run(&root, &["config", "show"]); + assert!(shown.status.success(), "{}", text(&shown.stderr)); + let config: Value = serde_json::from_slice(&shown.stdout).unwrap(); + assert_eq!(config["version"], 2); + assert_eq!(config["groups"][0]["id"], 0); + + let saved = run(&root, &["config", "save", "edited"]); + assert!(saved.status.success(), "{}", text(&saved.stderr)); + let listed = run(&root, &["config", "list"]); + assert!(listed.status.success(), "{}", text(&listed.stderr)); + let profiles_json: Value = serde_json::from_slice(&listed.stdout).unwrap(); + assert_eq!(profiles_json.as_array().unwrap().len(), 2); + assert_eq!(fs::read(&legacy).unwrap(), legacy_bytes); + assert_eq!(fs::read(&overrides).unwrap(), override_bytes); +} + +#[test] +fn config_reset_all_backup_refuses_a_future_schema_without_writing() { + let root = TestRoot::new("future-store"); + let profiles = root.profiles_path(); + fs::create_dir_all(profiles.parent().unwrap()).unwrap(); + let original = br#"{"version":99,"active_profile":"default","profiles":[]}"#.to_vec(); + fs::write(&profiles, &original).unwrap(); + let (legacy, legacy_bytes, overrides, override_bytes) = write_profile_neighbors(&root); + + let output = run(&root, &["config", "reset", "--all", "--backup"]); + assert_eq!(output.status.code(), Some(1), "{}", text(&output.stdout)); + let stderr = text(&output.stderr); + assert!(stderr.contains("newer than this SBMS"), "{stderr}"); + assert!(stderr.contains("left unchanged"), "{stderr}"); + assert!( + !stderr.contains("configuration recovery was committed"), + "{stderr}" + ); + assert!( + !stderr.contains("sbms config reset --all --backup"), + "{stderr}" + ); + assert_eq!(text(&output.stdout), ""); + assert_eq!(fs::read(&profiles).unwrap(), original); + assert!(recovery_backups(&root).is_empty()); + assert_eq!(fs::read(&legacy).unwrap(), legacy_bytes); + assert_eq!(fs::read(&overrides).unwrap(), override_bytes); +} + +#[test] +fn config_reset_changes_only_the_active_profile() { + let root = TestRoot::new("reset-active"); + let office_path = root.path().join("office.json"); + let gaming_path = root.path().join("gaming.json"); + let office = json!({ + "version": 2, + "groups": [{ + "id": 0, + "route": {"kind": "mirror", "target_id": "office-display"} + }], + "selected_group_id": 0 + }); + let gaming = json!({ + "version": 2, + "groups": [{ + "id": 0, + "route": {"kind": "mirror", "target_id": "gaming-display"} + }], + "selected_group_id": 0 + }); + fs::write(&office_path, serde_json::to_vec_pretty(&office).unwrap()).unwrap(); + fs::write(&gaming_path, serde_json::to_vec_pretty(&gaming).unwrap()).unwrap(); + assert!(run(&root, &["config", "show"]).status.success()); + let replace_default = run( + &root, + &[ + "config", + "import", + "default", + office_path.to_str().unwrap(), + "--replace", + ], + ); + assert!( + replace_default.status.success(), + "{}", + text(&replace_default.stderr) + ); + let activate_gaming = run( + &root, + &[ + "config", + "import", + "gaming", + gaming_path.to_str().unwrap(), + "--activate", + ], + ); + assert!( + activate_gaming.status.success(), + "{}", + text(&activate_gaming.stderr) + ); + + let reset = run(&root, &["config", "reset"]); + assert!(reset.status.success(), "{}", text(&reset.stderr)); + assert!(text(&reset.stdout).starts_with("reset=gaming revision=2 reload=")); + assert!(recovery_backups(&root).is_empty()); + + let active = run(&root, &["config", "show"]); + let active_config: Value = serde_json::from_slice(&active.stdout).unwrap(); + assert_eq!( + active_config["groups"][0]["route"], + json!({"kind": "mirror"}) + ); + let preserved = run(&root, &["config", "show", "default"]); + assert_eq!( + serde_json::from_slice::(&preserved.stdout).unwrap(), + office + ); + let listed = serde_json::from_slice::(&run(&root, &["config", "list"]).stdout).unwrap(); + assert_eq!(listed.as_array().unwrap().len(), 2); + assert!( + listed + .as_array() + .unwrap() + .iter() + .any(|profile| { profile["id"] == "gaming" && profile["active"] == true }) + ); +} + #[test] fn plan_validation_reports_valid_and_empty_plans() { let root = TestRoot::new("plan"); From e8b8d2bf9d1768a60423239b46b7939143a29b4a Mon Sep 17 00:00:00 2001 From: Nardo021 Date: Tue, 3 Nov 2026 13:43:02 +1100 Subject: [PATCH 2/2] fix: reject a stale snapshot after a profile name is reused A deleted profile rebuilt under the same name kept revision 1, so an old snapshot still passed the save check and overwrote the new profile. Co-authored-by: Cursor --- docs/architecture.md | 2 + docs/configuration.md | 62 ++++- src/config.rs | 589 +++++++++++++++++++++++++++++++++++++++--- src/ui.rs | 1 + 4 files changed, 608 insertions(+), 46 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 61a8822..83ad5d0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -92,6 +92,8 @@ claims; it never performs an implicit second window restoration. User configuration is stored as at most three named profiles in `%LOCALAPPDATA%\SBMS\config-profiles-v1.json`. The collection, active profile and per-profile revisions are committed atomically under a cross-process lock. +Each profile also has an instance id that is not reused when a deleted name +is created again. Saves compare that id together with the revision. On first use, the existing `config-v2.json` is preserved and imported as the `default` profile. The tray supports revision-checked live reloads without changing a mapping that is already running. A damaged profile collection is diff --git a/docs/configuration.md b/docs/configuration.md index cb49f61..62fb5ac 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1,11 +1,13 @@ # Configuration profiles SBMS stores up to three persistent configuration profiles in -`%LOCALAPPDATA%\SBMS\config-profiles-v1.json`. The complete profile collection, -the active profile identifier, every profile revision and every nested -`AppConfig` are committed as one pretty-printed JSON document. Writes use a -cross-process mutex, a same-directory temporary file, `sync_all`, and a -write-through atomic replacement. +`%LOCALAPPDATA%\SBMS\config-profiles-v1.json`. The file name stays +`config-profiles-v1.json`; the document inside it is version 2. The complete +profile collection, the active profile identifier, every profile instance id, +every profile revision and every nested `AppConfig` are committed as one +pretty-printed JSON document. Writes use a cross-process mutex, a +same-directory temporary file, `sync_all`, and a write-through atomic +replacement. The first profile operation imports the existing `config-v2.json` as the `default` profile. The legacy file is left unchanged. If the old file is @@ -75,7 +77,8 @@ notification failed. Ordinary profile commands, including `sbms config reset`, load the collection before changing it. A truncated file, invalid JSON, or a version 1 collection -that fails semantic validation therefore cannot be repaired by `reset`. +that fails semantic validation therefore cannot be repaired by `reset`. A +valid version 1 collection is migrated in place, as described below. `sbms config reset --all --backup` is the explicit recovery command. Under the existing cross-process profile lock it: @@ -92,11 +95,14 @@ The command discards every saved profile and both global preferences. It does not delete display overrides, logs, stream credentials, `config-v2.json`, or `config-v1.json`. -A numeric `version` greater than 1 is a newer schema. Recovery refuses it and +A numeric `version` greater than 2 is a newer schema. Recovery refuses it and leaves the file unchanged, without writing a backup. A non-numeric `version`, truncated JSON, or any other file whose schema version cannot be recognized is damaged. Only this command can rebuild it. The command also accepts a valid collection: it still backs up the raw bytes and replaces the whole collection. +The rebuilt collection receives new profile instance ids, so snapshots taken +before recovery no longer match. + Permission errors and other read/write failures are not treated as damage: the source file stays in place. If the backup itself fails, nothing is replaced. If the backup succeeds and the atomic replacement fails, the command reports @@ -110,6 +116,27 @@ sbms config reset --all --backup recovered=default revision=1 backup=%LOCALAPPDATA%\SBMS\config-profiles-v1.json.recovery--.bak reload=not-running ``` +## Profile instance migration + +A valid version 1 collection has no instance ids. The first operation that +loads it, under the existing profile lock, allocates one UUID version-4 +instance id per profile with `BCryptGenRandom` and atomically writes document +version 2. The following load reads those same ids. They are not generated +again during deserialization. + +If allocating an id or the atomic write fails, the version 1 file stays in +place and the call returns an error. It does not return a snapshot whose ids +were never stored. A version 1 document that already contains `instance_id`, +or that fails semantic validation, is damaged and is not migrated. A version 2 +document with an invalid or duplicate instance id is also rejected and left +unchanged. + +SBMS 2.0.2 cannot read a version 2 collection. Deserialization fails on the +unknown `instance_id` field, and that build accepts only document version 1. +The failure returns before any write, so the newer file stays in place. A +build that treats every numeric version greater than 1 as a newer schema also +leaves a version 2 file unchanged. + ## JSON exchange format Import and export use the existing standalone `AppConfig` version 2 format, @@ -133,7 +160,10 @@ not the internal multi-profile collection: Unknown fields, unsupported versions, empty or oversized group collections, duplicate group IDs or mirror targets, invalid geometry and invalid selected -group IDs are rejected before any persistent state changes. +group IDs are rejected before any persistent state changes. An import file +cannot carry a profile instance id. `instance_id` is rejected as an unknown +field. Replacing an existing profile keeps that profile's instance id and +increases its revision. Creating a profile allocates a new instance id. ## Rendering options @@ -180,10 +210,15 @@ controller reports both `running=false` and `busy=false`. Reload never restarts, stops or mutates the active mapping. It changes the configuration used by the next mapping start. -Each profile has a monotonically increasing revision. UI saves use a -profile-ID-and-revision compare-and-swap. A stale UI draft therefore cannot -overwrite a profile imported or activated by another process; the user must -reload before saving again. +Each profile has an instance id and a monotonically increasing revision. The +instance id is created with the profile. Copying a profile, deleting it and +creating the same name again, and rebuilding the whole collection all allocate +a new id. Renaming a profile, editing or replacing its contents, and +`sbms config reset` keep the id and increase the revision. UI saves compare +the active profile's name, instance id, and revision. A matching name and +revision are not enough after that name has been deleted and created again. +The save is refused with `Reload the configuration before saving`. The UI +shows that error and does not retry the stale draft. ## Rust interface @@ -198,7 +233,8 @@ The public API is exported from `sbms::config`: backup path. `ConfigError::allows_profile_collection_recovery` is true only for a damaged collection this build can rebuild. - `save_active_if_revision` is the compare-and-swap save operation for a pinned - UI session. + UI session. It accepts the save only when the active profile's name, + instance id, and revision all match the caller's snapshot. - `ConfigStore::load_strict` validates standalone import files; `save` writes standalone exports atomically. - `sbms::control::signal_config_reload` and `listen_for_config_reload` expose diff --git a/src/config.rs b/src/config.rs index 31dd9d6..cd6db8e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -10,6 +10,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use serde::{Deserialize, Serialize}; use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_ABANDONED, WAIT_FAILED, WAIT_OBJECT_0}; +use windows::Win32::Security::Cryptography::{BCRYPT_USE_SYSTEM_PREFERRED_RNG, BCryptGenRandom}; use windows::Win32::Storage::FileSystem::{ MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW, REPLACEFILE_WRITE_THROUGH, ReplaceFileW, @@ -27,7 +28,8 @@ use crate::limits::{ const CONFIG_VERSION: u32 = 2; const LEGACY_CONFIG_VERSION: u32 = 1; -const CONFIG_PROFILES_VERSION: u32 = 1; +const LEGACY_CONFIG_PROFILES_VERSION: u32 = 1; +const CONFIG_PROFILES_VERSION: u32 = 2; pub const RECOVER_PROFILE_COLLECTION_COMMAND: &str = "sbms config reset --all --backup"; pub const MAX_CONFIG_PROFILES: usize = 3; const DISPLAY_OVERRIDES_VERSION: u32 = 1; @@ -180,6 +182,7 @@ pub struct ConfigStore { #[serde(deny_unknown_fields)] pub struct ConfigProfile { pub id: String, + pub instance_id: String, pub revision: u64, pub config: AppConfig, } @@ -203,6 +206,7 @@ fn is_false(value: &bool) -> bool { #[derive(Clone, Debug, Eq, PartialEq)] pub struct ProfileRevision { pub id: String, + pub instance_id: String, pub revision: u64, } @@ -906,6 +910,12 @@ impl ConfigProfiles { validate_profile_id(&self.active_profile)?; for (index, profile) in self.profiles.iter().enumerate() { validate_profile_id(&profile.id)?; + if !valid_profile_instance_id(&profile.instance_id) { + return Err(ConfigError(format!( + "config profile {} has an invalid instance id", + profile.id + ))); + } if profile.revision == 0 { return Err(ConfigError(format!( "config profile {} has an invalid zero revision", @@ -921,6 +931,15 @@ impl ConfigProfiles { profile.id ))); } + if self.profiles[..index] + .iter() + .any(|other| other.instance_id == profile.instance_id) + { + return Err(ConfigError(format!( + "config profile instance id {} is duplicated", + profile.instance_id + ))); + } profile.config.validate()?; } if !self @@ -1049,16 +1068,22 @@ impl ConfigProfileStore { let mut profiles = self.load_or_initialize_locked()?; if !profiles.active_profile.eq_ignore_ascii_case(&expected.id) { return Err(ConfigError(format!( - "active config profile changed from {} to {}; reload before saving", + "active config profile changed from {} to {}. Reload the configuration before saving", expected.id, profiles.active_profile ))); } let profile = profiles .profile_mut(&expected.id) .expect("validated config profiles contain the active profile"); + if profile.instance_id != expected.instance_id { + return Err(ConfigError(format!( + "config profile {} was replaced by a different profile with the same name. Reload the configuration before saving", + profile.id + ))); + } if profile.revision != expected.revision { return Err(ConfigError(format!( - "config profile {} changed from revision {} to {}; reload before saving", + "config profile {} changed from revision {} to {}. Reload the configuration before saving", profile.id, expected.revision, profile.revision ))); } @@ -1100,11 +1125,12 @@ impl ConfigProfileStore { "cannot create config profile {id}; the {MAX_CONFIG_PROFILES}-profile limit is reached" ))); } - profiles.profiles.push(ConfigProfile { - id: id.into(), - revision: 1, - config: config.clone(), - }); + profiles.profiles.push(config_profile_with_instance( + &profiles.profiles, + id.into(), + 1, + config.clone(), + )?); profiles.profiles.len() - 1 }; if activate { @@ -1138,11 +1164,12 @@ impl ConfigProfileStore { "cannot create config profile {id}; the {MAX_CONFIG_PROFILES}-profile limit is reached" ))); } - profiles.profiles.push(ConfigProfile { - id: id.into(), - revision: 1, + profiles.profiles.push(config_profile_with_instance( + &profiles.profiles, + id.into(), + 1, config, - }); + )?); let result = snapshot(profiles.profiles.last().expect("profile was pushed")); self.save_locked(&profiles)?; Ok(result) @@ -1165,11 +1192,12 @@ impl ConfigProfileStore { ))); } let config = profiles.active().config.clone(); - profiles.profiles.push(ConfigProfile { - id: id.into(), - revision: 1, + profiles.profiles.push(config_profile_with_instance( + &profiles.profiles, + id.into(), + 1, config, - }); + )?); let index = profiles.profiles.len() - 1; if activate { profiles.active_profile = profiles.profiles[index].id.clone(); @@ -1294,7 +1322,7 @@ impl ConfigProfileStore { let mut profiles = if self.path.exists() { self.load_or_initialize_locked()? } else { - default_config_profiles() + default_config_profiles()? }; let active_id = profiles.active_profile.clone(); let profile = profiles @@ -1330,7 +1358,7 @@ impl ConfigProfileStore { // Flush the original bytes before replacing the store. A backup error // returns while the source file is still untouched. let backup = write_unique_profile_backup(&self.path, &bytes)?; - let profiles = default_config_profiles(); + let profiles = default_config_profiles()?; if let Err(error) = self.save_locked(&profiles) { return Err(ConfigError(format!( "config profile recovery was not committed; {}; backup remains at {}: {error}", @@ -1346,7 +1374,7 @@ impl ConfigProfileStore { fn load_or_initialize_locked(&self) -> Result { match fs::read(&self.path) { - Ok(bytes) => parse_profile_store(&self.path, &bytes), + Ok(bytes) => self.load_existing_locked(&bytes), Err(error) if error.kind() == std::io::ErrorKind::NotFound => { let legacy_store = ConfigStore { path: self.legacy_config_path.clone(), @@ -1368,7 +1396,7 @@ impl ConfigProfileStore { } Err(error) => return Err(error), }; - let profiles = single_profile_collection(config); + let profiles = single_profile_collection(config)?; self.save_locked(&profiles)?; Ok(profiles) } @@ -1383,6 +1411,70 @@ impl ConfigProfileStore { profiles.validate()?; save_json_atomically(&self.path, profiles, "config profiles", "config profiles") } + + fn load_existing_locked(&self, bytes: &[u8]) -> Result { + if let Some(version) = recognized_future_profiles_version(bytes) { + return Err(future_profile_store(&self.path, &version)); + } + if is_legacy_profile_collection(bytes) { + return self.migrate_legacy_profiles_locked(bytes); + } + parse_profile_store(&self.path, bytes) + } + + fn migrate_legacy_profiles_locked(&self, bytes: &[u8]) -> Result { + let legacy = serde_json::from_slice::(bytes) + .map_err(|error| damaged_profile_store(&self.path, error))?; + if legacy.version != LEGACY_CONFIG_PROFILES_VERSION { + return Err(damaged_profile_store( + &self.path, + format!("unsupported config profiles version {}", legacy.version), + )); + } + preview_legacy_collection(&legacy) + .validate() + .map_err(|error| damaged_profile_store(&self.path, error))?; + let profiles = assign_profile_instances(legacy)?; + self.persist_migrated_profiles(&profiles) + } + + fn persist_migrated_profiles( + &self, + profiles: &ConfigProfiles, + ) -> Result { + if let Err(error) = self.save_locked(profiles) { + return Err(ConfigError(format!( + "could not persist migrated config profile identities in {}: {error}", + self.path.display() + ))); + } + let bytes = fs::read(&self.path).map_err(|error| { + ConfigError(format!( + "migrated config profile identities were written to {} but could not be reloaded: {error}", + self.path.display() + )) + })?; + let persisted = parse_profile_store(&self.path, &bytes).map_err(|error| { + ConfigError(format!( + "migrated config profile identities were written to {} but could not be reloaded: {error}", + self.path.display() + )) + })?; + let identities_match = + persisted.profiles.len() == profiles.profiles.len() + && persisted.profiles.iter().zip(profiles.profiles.iter()).all( + |(saved, assigned)| { + saved.id == assigned.id && saved.instance_id == assigned.instance_id + }, + ); + if !identities_match { + return Err(ConfigError(format!( + "migrated config profile identities were written to {} but did not reload with the assigned identities", + self.path.display() + ))); + } + Ok(persisted) + } } impl CrossProcessConfigGuard { @@ -1463,24 +1555,173 @@ fn consume_profile_store_test_fault(expected: ProfileStoreTestFault) -> bool { }) } -fn single_profile_collection(config: AppConfig) -> ConfigProfiles { - ConfigProfiles { +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct LegacyConfigProfile { + id: String, + revision: u64, + config: AppConfig, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct LegacyConfigProfiles { + version: u32, + active_profile: String, + #[serde(default)] + launch_intro_disabled: bool, + #[serde(default)] + auto_map_on_login: bool, + profiles: Vec, +} + +fn single_profile_collection(config: AppConfig) -> Result { + Ok(ConfigProfiles { version: CONFIG_PROFILES_VERSION, active_profile: "default".into(), launch_intro_disabled: false, auto_map_on_login: false, - profiles: vec![ConfigProfile { - id: "default".into(), - revision: 1, + profiles: vec![config_profile_with_instance( + &[], + "default".into(), + 1, config, - }], - } + )?], + }) } -fn default_config_profiles() -> ConfigProfiles { +fn default_config_profiles() -> Result { single_profile_collection(AppConfig::default()) } +fn config_profile_with_instance( + existing: &[ConfigProfile], + id: String, + revision: u64, + config: AppConfig, +) -> Result { + Ok(ConfigProfile { + id, + instance_id: fresh_profile_instance_id(existing)?, + revision, + config, + }) +} + +fn preview_legacy_collection(legacy: &LegacyConfigProfiles) -> ConfigProfiles { + ConfigProfiles { + version: CONFIG_PROFILES_VERSION, + active_profile: legacy.active_profile.clone(), + launch_intro_disabled: legacy.launch_intro_disabled, + auto_map_on_login: legacy.auto_map_on_login, + profiles: legacy + .profiles + .iter() + .enumerate() + .map(|(index, profile)| ConfigProfile { + id: profile.id.clone(), + instance_id: format!("00000000-0000-4000-8000-{index:012x}"), + revision: profile.revision, + config: profile.config.clone(), + }) + .collect(), + } +} + +fn assign_profile_instances(legacy: LegacyConfigProfiles) -> Result { + let mut profiles = Vec::with_capacity(legacy.profiles.len()); + for profile in legacy.profiles { + profiles.push(config_profile_with_instance( + &profiles, + profile.id, + profile.revision, + profile.config, + )?); + } + Ok(ConfigProfiles { + version: CONFIG_PROFILES_VERSION, + active_profile: legacy.active_profile, + launch_intro_disabled: legacy.launch_intro_disabled, + auto_map_on_login: legacy.auto_map_on_login, + profiles, + }) +} + +fn fresh_profile_instance_id(existing: &[ConfigProfile]) -> Result { + for _ in 0..8 { + let instance_id = new_profile_instance_id()?; + if existing + .iter() + .all(|profile| profile.instance_id != instance_id) + { + return Ok(instance_id); + } + } + Err(ConfigError( + "could not allocate a unique config profile instance id".into(), + )) +} + +fn new_profile_instance_id() -> Result { + let mut bytes = [0u8; 16]; + let status = unsafe { BCryptGenRandom(None, &mut bytes, BCRYPT_USE_SYSTEM_PREFERRED_RNG) }; + if status.0 < 0 { + return Err(ConfigError(format!( + "could not allocate a config profile instance id: BCryptGenRandom failed: 0x{:08x}", + status.0 as u32 + ))); + } + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + Ok(format_profile_instance_id(&bytes)) +} + +fn format_profile_instance_id(bytes: &[u8; 16]) -> String { + format!( + "{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", + bytes[0], + bytes[1], + bytes[2], + bytes[3], + bytes[4], + bytes[5], + bytes[6], + bytes[7], + bytes[8], + bytes[9], + bytes[10], + bytes[11], + bytes[12], + bytes[13], + bytes[14], + bytes[15] + ) +} + +fn valid_profile_instance_id(instance_id: &str) -> bool { + let bytes = instance_id.as_bytes(); + if bytes.len() != 36 { + return false; + } + let mut index = 0; + for (group, length) in [8, 4, 4, 4, 12].into_iter().enumerate() { + if group > 0 { + if bytes[index] != b'-' { + return false; + } + index += 1; + } + if !bytes[index..index + length] + .iter() + .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) + { + return false; + } + index += length; + } + bytes[14] == b'4' && matches!(bytes[19], b'8' | b'9' | b'a' | b'b') +} + fn damaged_profile_store(path: &Path, detail: impl Display) -> ConfigError { let path = path.display(); ConfigError(format!( @@ -1495,10 +1736,19 @@ fn future_profile_store(path: &Path, version: &str) -> ConfigError { )) } -fn recognized_future_profiles_version(bytes: &[u8]) -> Option { +fn profiles_version_number(bytes: &[u8]) -> Option { let mut deserializer = serde_json::Deserializer::from_slice(bytes); let value = serde_json::Value::deserialize(&mut deserializer).ok()?; - let version = value.as_object()?.get("version")?.as_number()?; + value.as_object()?.get("version")?.as_number().cloned() +} + +fn is_legacy_profile_collection(bytes: &[u8]) -> bool { + profiles_version_number(bytes).and_then(|version| version.as_u64()) + == Some(u64::from(LEGACY_CONFIG_PROFILES_VERSION)) +} + +fn recognized_future_profiles_version(bytes: &[u8]) -> Option { + let version = profiles_version_number(bytes)?; if let Some(integer) = version.as_u64() { return (integer > u64::from(CONFIG_PROFILES_VERSION)).then(|| integer.to_string()); } @@ -1625,6 +1875,7 @@ fn snapshot(profile: &ConfigProfile) -> ProfileSnapshot { ProfileSnapshot { profile: ProfileRevision { id: profile.id.clone(), + instance_id: profile.instance_id.clone(), revision: profile.revision, }, config: profile.config.clone(), @@ -2492,13 +2743,21 @@ mod tests { profiles.duplicate_active("gaming", false).unwrap(); profiles.duplicate_active("streaming", false).unwrap(); + let gaming = profiles.load_profile("gaming").unwrap(); + assert_ne!(gaming.profile.instance_id, original.profile.instance_id); + let (case_changed, case_changed_active) = profiles.rename("default", "DEFAULT").unwrap(); assert!(case_changed_active); assert_eq!(case_changed.profile.id, "DEFAULT"); + assert_eq!( + case_changed.profile.instance_id, + original.profile.instance_id + ); assert_eq!(case_changed.profile.revision, original.profile.revision + 1); assert_eq!(case_changed.config, original.config); let (renamed, renamed_active) = profiles.rename("DEFAULT", "primary").unwrap(); + assert_eq!(renamed.profile.instance_id, original.profile.instance_id); assert!(renamed_active); assert_eq!(profiles.load_active().unwrap(), renamed); assert!(profiles.load_profile("default").is_err()); @@ -2546,6 +2805,256 @@ mod tests { fs::remove_dir_all(root).unwrap(); } + #[test] + fn recreated_profile_rejects_a_snapshot_from_the_deleted_instance() { + let (root, store) = test_profile_store("recreated-instance"); + store.load_active().unwrap(); + let (created, active) = store + .save_profile("gaming", &config_with_target("old-gaming"), false, true) + .unwrap(); + assert!(active); + assert_eq!(created.profile.id, "gaming"); + assert_eq!(created.profile.revision, 1); + let snapshot_a = store.load_active().unwrap(); + assert_eq!(snapshot_a, created); + + store.activate("default").unwrap(); + store.delete("gaming").unwrap(); + let (recreated, active) = store + .save_profile("gaming", &config_with_target("new-gaming"), false, true) + .unwrap(); + assert!(active); + assert_eq!(recreated.profile.revision, 1); + let snapshot_b = store.load_active().unwrap(); + assert_eq!(snapshot_b, recreated); + assert_eq!(snapshot_b.config, config_with_target("new-gaming")); + assert_ne!( + snapshot_a.profile.instance_id, + snapshot_b.profile.instance_id + ); + + let error = store + .save_active_if_revision(&snapshot_a.profile, &config_with_target("stale-gaming")) + .unwrap_err(); + let message = error.to_string(); + assert!( + message.contains("Reload the configuration before saving"), + "{message}" + ); + let unchanged = store.load_active().unwrap(); + assert_eq!(unchanged, snapshot_b); + + let saved = store + .save_active_if_revision(&snapshot_b.profile, &config_with_target("saved-gaming")) + .unwrap(); + assert_eq!(saved.profile.instance_id, snapshot_b.profile.instance_id); + assert_eq!(saved.profile.revision, snapshot_b.profile.revision + 1); + assert_eq!(saved.config, config_with_target("saved-gaming")); + assert_eq!(store.load_active().unwrap(), saved); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn current_instance_snapshot_saves_and_keeps_its_identity() { + let (root, store) = test_profile_store("current-instance"); + let current = store.load_active().unwrap(); + let saved = store + .save_active_if_revision(¤t.profile, &config_with_target("kept-target")) + .unwrap(); + assert_eq!(saved.profile.instance_id, current.profile.instance_id); + assert_eq!(saved.profile.revision, current.profile.revision + 1); + assert_eq!(saved.config, config_with_target("kept-target")); + assert_eq!(store.load_active().unwrap(), saved); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn legacy_profile_collection_keeps_assigned_instance_ids_after_reload() { + let (root, store) = test_profile_store("legacy-ids"); + store.load_active().unwrap(); + store.set_launch_intro_disabled(true).unwrap(); + store.set_auto_map_on_login(true).unwrap(); + store + .save_profile( + "gaming", + &config_with_target("gaming-display"), + false, + false, + ) + .unwrap(); + let legacy = legacy_collection_without_instance_ids(&store); + fs::write(store.path(), &legacy).unwrap(); + + let first = store.list().unwrap(); + assert_eq!(first.version, 2); + assert!(first.launch_intro_disabled); + assert!(first.auto_map_on_login); + assert_eq!(first.profiles.len(), 2); + assert_ne!(first.profiles[0].instance_id, first.profiles[1].instance_id); + assert_eq!( + first.profile("gaming").unwrap().config, + config_with_target("gaming-display") + ); + let migrated = fs::read(store.path()).unwrap(); + assert_ne!(migrated, legacy); + + assert_eq!(store.list().unwrap(), first); + assert_eq!(fs::read(store.path()).unwrap(), migrated); + + let mut smuggled: serde_json::Value = serde_json::from_slice(&legacy).unwrap(); + smuggled["profiles"][0]["instance_id"] = + serde_json::json!("00000000-0000-4000-8000-000000000001"); + let smuggled_bytes = serde_json::to_vec_pretty(&smuggled).unwrap(); + fs::write(store.path(), &smuggled_bytes).unwrap(); + let error = store.load_active().unwrap_err(); + assert!(error.allows_profile_collection_recovery(), "{error}"); + assert_eq!(fs::read(store.path()).unwrap(), smuggled_bytes); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn legacy_profile_migration_keeps_the_source_when_replacement_fails() { + let (root, store) = test_profile_store("legacy-replace-fails"); + store.load_active().unwrap(); + let legacy = legacy_collection_without_instance_ids(&store); + fs::write(store.path(), &legacy).unwrap(); + let _fault = inject_profile_store_fault(ProfileStoreTestFault::Replace); + let error = store.load_active().unwrap_err(); + drop(_fault); + let message = error.to_string(); + assert!( + message.contains("could not persist migrated config profile identities"), + "{message}" + ); + assert!(!error.allows_profile_collection_recovery(), "{message}"); + assert_eq!(fs::read(store.path()).unwrap(), legacy); + + let loaded = store.load_active().unwrap(); + assert_eq!(loaded.profile.id, "default"); + assert!(valid_profile_instance_id(&loaded.profile.instance_id)); + assert_eq!(store.load_active().unwrap(), loaded); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn profile_collection_recovery_rejects_snapshots_taken_before_it() { + let (root, store) = test_profile_store("recovery-identity"); + let before = store.load_active().unwrap(); + let recovered = store.recover_with_backup().unwrap(); + assert_eq!(recovered.snapshot.profile.id, before.profile.id); + assert_eq!(recovered.snapshot.profile.revision, before.profile.revision); + assert_ne!( + recovered.snapshot.profile.instance_id, + before.profile.instance_id + ); + + let error = store + .save_active_if_revision(&before.profile, &config_with_target("old-default")) + .unwrap_err(); + assert!( + error + .to_string() + .contains("Reload the configuration before saving"), + "{error}" + ); + assert_eq!(store.load_active().unwrap(), recovered.snapshot); + + let saved = store + .save_active_if_revision( + &recovered.snapshot.profile, + &config_with_target("new-default"), + ) + .unwrap(); + assert_eq!( + saved.profile.instance_id, + recovered.snapshot.profile.instance_id + ); + assert_eq!(store.load_active().unwrap(), saved); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn imported_app_config_cannot_supply_a_profile_instance_id() { + let (root, store) = test_profile_store("import-identity"); + let (created, _) = store + .save_profile("gaming", &config_with_target("old-gaming"), false, true) + .unwrap(); + let (replaced, _) = store + .save_profile("gaming", &config_with_target("new-gaming"), true, true) + .unwrap(); + assert_eq!(replaced.profile.instance_id, created.profile.instance_id); + assert_eq!(replaced.profile.revision, created.profile.revision + 1); + + let export_path = root.join("export.json"); + ConfigStore::new(export_path.clone()) + .save(&replaced.config) + .unwrap(); + let exported: serde_json::Value = + serde_json::from_slice(&fs::read(&export_path).unwrap()).unwrap(); + assert!(exported.get("instance_id").is_none()); + + let mut document = exported; + document.as_object_mut().unwrap().insert( + "instance_id".into(), + serde_json::json!(created.profile.instance_id), + ); + let import_path = root.join("import.json"); + fs::write(&import_path, serde_json::to_vec_pretty(&document).unwrap()).unwrap(); + let error = ConfigStore::new(import_path).load_strict().unwrap_err(); + assert!(error.to_string().contains("instance_id"), "{error}"); + assert_eq!( + store.load_profile("gaming").unwrap().profile.instance_id, + created.profile.instance_id + ); + assert_eq!( + store.load_profile("gaming").unwrap().config, + config_with_target("new-gaming") + ); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn version_two_rejects_invalid_or_duplicate_instance_ids_without_writing() { + let (root, store) = test_profile_store("bad-instance"); + store.load_active().unwrap(); + store + .save_profile( + "gaming", + &config_with_target("gaming-display"), + false, + false, + ) + .unwrap(); + let mut value: serde_json::Value = + serde_json::from_slice(&fs::read(store.path()).unwrap()).unwrap(); + value["profiles"][0]["instance_id"] = serde_json::json!("not-an-instance"); + let invalid = serde_json::to_vec_pretty(&value).unwrap(); + fs::write(store.path(), &invalid).unwrap(); + let error = store.load_active().unwrap_err(); + assert!(error.allows_profile_collection_recovery(), "{error}"); + assert!(error.to_string().contains("invalid instance id"), "{error}"); + assert_eq!(fs::read(store.path()).unwrap(), invalid); + + value["profiles"][0]["instance_id"] = value["profiles"][1]["instance_id"].clone(); + let duplicated = serde_json::to_vec_pretty(&value).unwrap(); + fs::write(store.path(), &duplicated).unwrap(); + let error = store.load_active().unwrap_err(); + assert!(error.to_string().contains("duplicated"), "{error}"); + assert!(error.allows_profile_collection_recovery(), "{error}"); + assert_eq!(fs::read(store.path()).unwrap(), duplicated); + fs::remove_dir_all(root).unwrap(); + } + + fn legacy_collection_without_instance_ids(store: &ConfigProfileStore) -> Vec { + let mut value: serde_json::Value = + serde_json::from_slice(&fs::read(store.path()).unwrap()).unwrap(); + value["version"] = serde_json::json!(LEGACY_CONFIG_PROFILES_VERSION); + for profile in value["profiles"].as_array_mut().unwrap() { + profile.as_object_mut().unwrap().remove("instance_id"); + } + serde_json::to_vec_pretty(&value).unwrap() + } + #[test] fn stale_profile_revision_cannot_overwrite_reloaded_config() { let (root, profiles) = test_profile_store("revision"); @@ -2561,7 +3070,12 @@ mod tests { .save_active_if_revision(&stale.profile, &config_with_target("stale-target")) .unwrap_err(); - assert!(error.to_string().contains("changed from revision")); + let message = error.to_string(); + assert!(message.contains("changed from revision"), "{message}"); + assert!( + message.contains("Reload the configuration before saving"), + "{message}" + ); assert_eq!(profiles.load_active().unwrap(), updated); fs::remove_dir_all(root).unwrap(); } @@ -2839,9 +3353,9 @@ mod tests { "version-99", br#"{"version":99,"active_profile":"default","profiles":[]}"#, ), - ("version-2-extra", br#"{"version":2,"extra":true}"#), + ("version-3-extra", br#"{"version":3,"extra":true}"#), ("version-prefix", br#"{"version":99} trailing"#), - ("version-float", br#"{"version":1.5,"profiles":[]}"#), + ("version-float", br#"{"version":2.5,"profiles":[]}"#), ]; for (name, original) in cases { let (root, store) = prepare_profile_bytes(name, original); @@ -2925,8 +3439,17 @@ mod tests { .save_profile("gaming", &config_with_target("gaming-display"), false, true) .unwrap(); + let gaming_before = store.load_profile("gaming").unwrap(); let snapshot = store.reset_active().unwrap(); assert_eq!(snapshot.profile.id, "gaming"); + assert_eq!( + snapshot.profile.instance_id, + gaming_before.profile.instance_id + ); + assert_eq!( + snapshot.profile.revision, + gaming_before.profile.revision + 1 + ); assert_eq!(snapshot.config, AppConfig::default()); let profiles = store.list().unwrap(); assert_eq!(profiles.profiles.len(), 2); diff --git a/src/ui.rs b/src/ui.rs index 50a16d9..7ae3030 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -1496,6 +1496,7 @@ fn default_loaded_groups() -> LoadedGroups { active: 0, profile: ProfileRevision { id: "default".into(), + instance_id: String::new(), revision: 0, }, }