From a2df328d0bafa3dc75071bb999b79ec66a57e079 Mon Sep 17 00:00:00 2001 From: fufesou Date: Mon, 12 Oct 2026 21:59:19 -0700 Subject: [PATCH 01/11] fix: preserve trusted-device grants in Config2 Add fallible grant persistence with file locking and atomic replacement. Preserve the persisted grant state during ordinary settings writes so stale configuration snapshots cannot restore revoked devices. Signed-off-by: fufesou --- Cargo.toml | 3 + src/config.rs | 41 +++++++++- src/config/file_storage.rs | 162 +++++++++++++++++++++++++++++++++++++ 3 files changed, 204 insertions(+), 2 deletions(-) create mode 100644 src/config/file_storage.rs diff --git a/Cargo.toml b/Cargo.toml index e8a722802..7a8c3ec53 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -90,3 +90,6 @@ webrtc = "0.13.0" # keep in lockstep with [dependencies] webrtc (rustc 1.75 pin, [target.'cfg(target_os = "linux")'.dependencies] users = { version = "0.11" } x11 = "2.21" + +[target.'cfg(target_os = "windows")'.dependencies] +windows = { version = "0.61", features = ["Win32_Storage_FileSystem", "Win32_System_IO", "Win32_Security"] } diff --git a/src/config.rs b/src/config.rs index 6fe100455..efeb4b8c7 100644 --- a/src/config.rs +++ b/src/config.rs @@ -19,7 +19,9 @@ use serde_json; use sodiumoxide::base64; use sodiumoxide::crypto::sign; +mod file_storage; mod permanent_password; +pub use file_storage::FileStorage; pub use permanent_password::{ compute_permanent_password_h1, decode_permanent_password_h1_from_storage, @@ -249,6 +251,13 @@ pub struct Config2 { #[serde(default, deserialize_with = "deserialize_string")] trusted_devices: String, + #[serde( + default, + deserialize_with = "deserialize_string", + skip_serializing_if = "String::is_empty" + )] + trusted_devices_v2: String, + #[serde(default)] socks: Option, @@ -512,8 +521,17 @@ impl Config2 { } fn store(&self) { + if let Err(error) = self.try_store() { + log::error!("Failed to store config2: {error}"); + } + } + + fn try_store(&self) -> crate::ResultType<()> { + let storage = FileStorage::lock(&Self::file())?; let mut config = self.clone(); - let stored = Config::load_::("2"); + let stored: Config2 = storage.read_toml()?; + // Ordinary settings and stale process snapshots must never restore grants. + config.trusted_devices_v2 = stored.trusted_devices_v2; if let Some(mut socks) = config.socks { let stored_password = stored .socks @@ -526,7 +544,26 @@ impl Config2 { } config.unlock_pin = keep_encrypted_storage_if_plaintext_unchanged(&config.unlock_pin, &stored.unlock_pin); - Config::store_(&config, "2"); + storage.write_toml(&config) + } + + pub fn get_trusted_devices_v2() -> crate::ResultType { + let config: Self = FileStorage::lock(&Self::file())?.read_toml()?; + Ok(config.trusted_devices_v2) + } + + pub fn set_trusted_devices_v2(value: String) -> crate::ResultType<()> { + let storage = FileStorage::lock(&Self::file())?; + let mut config: Self = storage.read_toml()?; + config.trusted_devices_v2 = value; + storage.write_toml(&config) + } + + pub fn without_trusted_devices_v2(self) -> Self { + Self { + trusted_devices_v2: String::new(), + ..self + } } pub fn get() -> Config2 { diff --git a/src/config/file_storage.rs b/src/config/file_storage.rs new file mode 100644 index 000000000..fdf05b896 --- /dev/null +++ b/src/config/file_storage.rs @@ -0,0 +1,162 @@ +use crate::{anyhow::Context, ResultType}; +use serde::{de::DeserializeOwned, Serialize}; +use std::{ + fs::{self, File, OpenOptions}, + io::{ErrorKind, Write}, + path::{Path, PathBuf}, +}; + +#[cfg(unix)] +const PRIVATE_DIRECTORY_MODE: u32 = 0o700; +#[cfg(unix)] +const PRIVATE_FILE_MODE: u32 = 0o600; + +pub struct FileStorage { + path: PathBuf, + _lock: File, +} + +impl FileStorage { + pub fn lock(path: &Path) -> ResultType { + let parent = path + .parent() + .ok_or_else(|| crate::anyhow::anyhow!("Missing credential directory"))?; + let mut directories = fs::DirBuilder::new(); + directories.recursive(true); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + directories.mode(PRIVATE_DIRECTORY_MODE); + } + directories + .create(parent) + .context("Create trusted-device credential directory")?; + let lock = lock_file(&path.with_extension("lock"))?; + Ok(Self { + path: path.to_owned(), + _lock: lock, + }) + } + + pub fn read(&self) -> ResultType { + match File::open(&self.path) { + Ok(file) => serde_json::from_reader(file).context("Read trusted-device credentials"), + Err(error) if error.kind() == ErrorKind::NotFound => Ok(T::default()), + Err(error) => Err(error).context("Open trusted-device credentials"), + } + } + + pub fn read_toml(&self) -> ResultType { + match fs::read_to_string(&self.path) { + Ok(value) => crate::toml::from_str(&value) + .map_err(|_| crate::anyhow::anyhow!("Invalid configuration file")), + Err(error) if error.kind() == ErrorKind::NotFound => Ok(T::default()), + Err(error) => Err(error).context("Open configuration file"), + } + } + + pub fn write_toml(&self, value: &T) -> ResultType<()> { + let value = crate::toml::to_string(value).context("Encode configuration update")?; + self.write_with(|file| Ok(file.write_all(value.as_bytes())?)) + } + + pub fn write(&self, value: &T) -> ResultType<()> { + self.write_with(|file| { + serde_json::to_writer(file, value).context("Encode trusted-device credential update") + }) + } + + fn write_with(&self, write: impl FnOnce(&mut File) -> ResultType<()>) -> ResultType<()> { + let temporary = self + .path + .with_extension(format!("{}.tmp", crate::uuid::Uuid::new_v4())); + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(PRIVATE_FILE_MODE); + } + let mut file = options + .open(&temporary) + .context("Create trusted-device credential update")?; + write(&mut file)?; + file.sync_all() + .context("Persist trusted-device credential update")?; + #[cfg(not(windows))] + fs::rename(&temporary, &self.path).context("Commit trusted-device credential update")?; + #[cfg(windows)] + replace_file(&temporary, &self.path)?; + #[cfg(unix)] + if let Some(parent) = self.path.parent() { + File::open(parent)? + .sync_all() + .context("Persist trusted-device credential directory")?; + } + Ok(()) + } +} + +fn lock_file(path: &Path) -> ResultType { + let mut options = OpenOptions::new(); + options.read(true).write(true).create(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options + .mode(PRIVATE_FILE_MODE) + .custom_flags(crate::libc::O_NOFOLLOW | crate::libc::O_CLOEXEC); + } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + use windows::Win32::Storage::FileSystem::{FILE_SHARE_READ, FILE_SHARE_WRITE}; + options.share_mode(FILE_SHARE_READ.0 | FILE_SHARE_WRITE.0); + } + let file = options + .open(path) + .context("Lock trusted-device credentials")?; + #[cfg(unix)] + { + use std::os::fd::AsRawFd; + let result = unsafe { crate::libc::flock(file.as_raw_fd(), crate::libc::LOCK_EX) }; + if result != 0 { + return Err(std::io::Error::last_os_error()).context("Lock trusted-device credentials"); + } + } + #[cfg(windows)] + lock_windows_file(&file)?; + Ok(file) +} + +#[cfg(windows)] +fn lock_windows_file(file: &File) -> ResultType<()> { + use std::os::windows::io::AsRawHandle; + use windows::Win32::{Foundation::HANDLE, Storage::FileSystem, System::IO::OVERLAPPED}; + const LOCK_BYTES: u32 = 1; + // This is a synchronous handle: wait for the lock; closing the handle releases it. + unsafe { + FileSystem::LockFileEx( + HANDLE(file.as_raw_handle()), + FileSystem::LOCKFILE_EXCLUSIVE_LOCK, + None, + LOCK_BYTES, + 0, + &mut OVERLAPPED::default(), + ) + } + .context("Lock trusted-device credentials") +} + +#[cfg(windows)] +fn replace_file(source: &Path, destination: &Path) -> ResultType<()> { + use windows::{core::HSTRING, Win32::Storage::FileSystem}; + unsafe { + FileSystem::MoveFileExW( + &HSTRING::from(source), + &HSTRING::from(destination), + FileSystem::MOVEFILE_REPLACE_EXISTING | FileSystem::MOVEFILE_WRITE_THROUGH, + ) + } + .context("Commit trusted-device credential update") +} From 8791bf0d3398c14f6bb79f2a7bdfbce8e37b1117 Mon Sep 17 00:00:00 2001 From: fufesou Date: Tue, 13 Oct 2026 18:18:38 -0700 Subject: [PATCH 02/11] fix: simplify trusted-device configuration storage Signed-off-by: fufesou --- Cargo.toml | 3 - src/config.rs | 148 +++++++++++++-------------------- src/config/file_storage.rs | 162 ------------------------------------- 3 files changed, 54 insertions(+), 259 deletions(-) delete mode 100644 src/config/file_storage.rs diff --git a/Cargo.toml b/Cargo.toml index 7a8c3ec53..e8a722802 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -90,6 +90,3 @@ webrtc = "0.13.0" # keep in lockstep with [dependencies] webrtc (rustc 1.75 pin, [target.'cfg(target_os = "linux")'.dependencies] users = { version = "0.11" } x11 = "2.21" - -[target.'cfg(target_os = "windows")'.dependencies] -windows = { version = "0.61", features = ["Win32_Storage_FileSystem", "Win32_System_IO", "Win32_Security"] } diff --git a/src/config.rs b/src/config.rs index efeb4b8c7..c6354099e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -10,7 +10,6 @@ use std::{ }; use anyhow::{anyhow, Result}; -use bytes::Bytes; use rand::Rng; use regex::Regex; use serde as de; @@ -19,9 +18,7 @@ use serde_json; use sodiumoxide::base64; use sodiumoxide::crypto::sign; -mod file_storage; mod permanent_password; -pub use file_storage::FileStorage; pub use permanent_password::{ compute_permanent_password_h1, decode_permanent_password_h1_from_storage, @@ -67,7 +64,6 @@ lazy_static::lazy_static! { static ref CONFIG2: RwLock = RwLock::new(Config2::load()); static ref LOCAL_CONFIG: RwLock = RwLock::new(LocalConfig::load()); static ref STATUS: RwLock = RwLock::new(Status::load()); - static ref TRUSTED_DEVICES: RwLock<(Vec, bool)> = Default::default(); static ref ONLINE: Mutex> = Default::default(); pub static ref PROD_RENDEZVOUS_SERVER: RwLock = RwLock::new("".to_owned()); pub static ref EXE_RENDEZVOUS_SERVER: RwLock = Default::default(); @@ -248,9 +244,6 @@ pub struct Config2 { serial: i32, #[serde(default, deserialize_with = "deserialize_string")] unlock_pin: String, - #[serde(default, deserialize_with = "deserialize_string")] - trusted_devices: String, - #[serde( default, deserialize_with = "deserialize_string", @@ -276,6 +269,8 @@ pub struct Resolution { pub struct PeerConfig { #[serde(default, deserialize_with = "deserialize_vec_u8")] pub password: Vec, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub trusted_device_v2: String, #[serde(default, deserialize_with = "deserialize_size")] pub size: Size, #[serde(default, deserialize_with = "deserialize_size")] @@ -403,6 +398,7 @@ impl Default for PeerConfig { fn default() -> Self { Self { password: Default::default(), + trusted_device_v2: Default::default(), size: Default::default(), size_ft: Default::default(), size_pf: Default::default(), @@ -527,10 +523,9 @@ impl Config2 { } fn try_store(&self) -> crate::ResultType<()> { - let storage = FileStorage::lock(&Self::file())?; let mut config = self.clone(); - let stored: Config2 = storage.read_toml()?; - // Ordinary settings and stale process snapshots must never restore grants. + let stored: Config2 = try_load_path(Self::file())?; + // Ordinary settings must not restore grants from a stale snapshot. config.trusted_devices_v2 = stored.trusted_devices_v2; if let Some(mut socks) = config.socks { let stored_password = stored @@ -544,19 +539,20 @@ impl Config2 { } config.unlock_pin = keep_encrypted_storage_if_plaintext_unchanged(&config.unlock_pin, &stored.unlock_pin); - storage.write_toml(&config) + store_path(Self::file(), config) } pub fn get_trusted_devices_v2() -> crate::ResultType { - let config: Self = FileStorage::lock(&Self::file())?.read_toml()?; + let _lock = CONFIG2.read().unwrap(); + let config: Self = try_load_path(Self::file())?; Ok(config.trusted_devices_v2) } pub fn set_trusted_devices_v2(value: String) -> crate::ResultType<()> { - let storage = FileStorage::lock(&Self::file())?; - let mut config: Self = storage.read_toml()?; + let _lock = CONFIG2.write().unwrap(); + let mut config: Self = try_load_path(Self::file())?; config.trusted_devices_v2 = value; - storage.write_toml(&config) + store_path(Self::file(), config) } pub fn without_trusted_devices_v2(self) -> Self { @@ -589,6 +585,21 @@ fn keep_encrypted_storage_if_plaintext_unchanged(plain: &str, stored: &str) -> S encrypt_str_or_original(plain, PASSWORD_ENC_VERSION, ENCRYPT_MAX_LEN) } +fn try_load_path( + path: PathBuf, +) -> crate::ResultType { + match confy::load_path(path) { + Ok(config) => Ok(config), + Err(confy::ConfyError::GeneralLoadError(error)) + if error.kind() == std::io::ErrorKind::NotFound => + { + Ok(T::default()) + } + Err(confy::ConfyError::BadTomlData(_)) => Err(anyhow!("Invalid configuration file")), + Err(error) => Err(error.into()), + } +} + pub fn load_path( file: PathBuf, ) -> T { @@ -1352,7 +1363,6 @@ impl Config { } config.password = stored; config.store(); - Self::clear_trusted_devices(); true } @@ -1388,7 +1398,6 @@ impl Config { } config.store(); - Self::clear_trusted_devices(); Ok(true) } @@ -1626,70 +1635,10 @@ impl Config { config.store(); } - pub fn get_trusted_devices_json() -> String { - serde_json::to_string(&Self::get_trusted_devices()).unwrap_or_default() - } - - pub fn get_trusted_devices() -> Vec { - let (devices, synced) = TRUSTED_DEVICES.read().unwrap().clone(); - if synced { - return devices; - } - let devices = CONFIG2.read().unwrap().trusted_devices.clone(); - let (devices, succ, store) = decrypt_str_or_original(&devices, PASSWORD_ENC_VERSION); - if succ { - let mut devices: Vec = - serde_json::from_str(&devices).unwrap_or_default(); - let len = devices.len(); - devices.retain(|d| !d.outdate()); - if store || devices.len() != len { - Self::set_trusted_devices(devices.clone()); - } - *TRUSTED_DEVICES.write().unwrap() = (devices.clone(), true); - devices - } else { - Default::default() - } - } - - fn set_trusted_devices(mut trusted_devices: Vec) { - trusted_devices.retain(|d| !d.outdate()); - let devices = serde_json::to_string(&trusted_devices).unwrap_or_default(); - let max_len = 1024 * 1024; - if devices.bytes().len() > max_len { - log::error!("Trusted devices too large: {}", devices.bytes().len()); - return; - } - let devices = encrypt_str_or_original(&devices, PASSWORD_ENC_VERSION, max_len); - let mut config = CONFIG2.write().unwrap(); - config.trusted_devices = devices; - config.store(); - *TRUSTED_DEVICES.write().unwrap() = (trusted_devices, true); - } - - pub fn add_trusted_device(device: TrustedDevice) { - let mut devices = Self::get_trusted_devices(); - devices.retain(|d| d.hwid != device.hwid); - devices.push(device); - Self::set_trusted_devices(devices); - } - - pub fn remove_trusted_devices(hwids: &Vec) { - let mut devices = Self::get_trusted_devices(); - devices.retain(|d| !hwids.contains(&d.hwid)); - Self::set_trusted_devices(devices); - } - - pub fn clear_trusted_devices() { - Self::set_trusted_devices(Default::default()); - } - pub fn get() -> Config { return CONFIG.read().unwrap().clone(); } - // TODO: `Config::set()` does not invalidate trusted devices when permanent password/salt changes. - // This matches historical behavior, but may need revisiting in a separate PR. pub fn set(cfg: Config) -> bool { let mut lock = CONFIG.write().unwrap(); if *lock == cfg { @@ -1734,6 +1683,7 @@ impl Config { } const PEERS: &str = "peers"; +static PEER_CONFIG_WRITE_LOCK: Mutex<()> = Mutex::new(()); impl PeerConfig { pub fn load(id: &str) -> PeerConfig { @@ -1757,6 +1707,8 @@ impl PeerConfig { if store { config.store_(id); } + // Credentials must not reach general-purpose peer settings or UI data. + config.trusted_device_v2.clear(); config } Err(err) => { @@ -1785,12 +1737,36 @@ impl PeerConfig { *v = encrypt_str_or_original(v, PASSWORD_ENC_VERSION, ENCRYPT_MAX_LEN) } } - if let Err(err) = store_path(Self::path(id), config) { + let result = (|| { + let _lock = PEER_CONFIG_WRITE_LOCK.lock().unwrap(); + // A stale settings snapshot must not overwrite a newly issued credential. + config.trusted_device_v2 = try_load_path::(Self::path(id))?.trusted_device_v2; + store_path(Self::path(id), config) + })(); + if let Err(err) = result { log::error!("Failed to store config: {}", err); } NEW_STORED_PEER_CONFIG.lock().unwrap().insert(id.to_owned()); } + pub fn get_trusted_device_v2(id: &str) -> crate::ResultType { + let _lock = PEER_CONFIG_WRITE_LOCK.lock().unwrap(); + let config: Self = try_load_path(Self::path(id))?; + Ok(config.trusted_device_v2) + } + + pub fn set_trusted_device_v2( + id: &str, + value: String, + info: PeerInfoSerde, + ) -> crate::ResultType<()> { + let _lock = PEER_CONFIG_WRITE_LOCK.lock().unwrap(); + let mut config: Self = try_load_path(Self::path(id))?; + config.trusted_device_v2 = value; + config.info = info; + store_path(Self::path(id), config) + } + pub fn remove(id: &str) { fs::remove_file(Self::path(id)).ok(); } @@ -2741,22 +2717,6 @@ impl Group { } } -#[derive(Debug, Default, Serialize, Deserialize, Clone)] -pub struct TrustedDevice { - pub hwid: Bytes, - pub time: i64, - pub id: String, - pub name: String, - pub platform: String, -} - -impl TrustedDevice { - pub fn outdate(&self) -> bool { - const DAYS_90: i64 = 90 * 24 * 60 * 60 * 1000; - self.time + DAYS_90 < crate::get_time() - } -} - deserialize_default!(deserialize_string, String); deserialize_default!(deserialize_bool, bool); deserialize_default!(deserialize_i32, i32); diff --git a/src/config/file_storage.rs b/src/config/file_storage.rs deleted file mode 100644 index fdf05b896..000000000 --- a/src/config/file_storage.rs +++ /dev/null @@ -1,162 +0,0 @@ -use crate::{anyhow::Context, ResultType}; -use serde::{de::DeserializeOwned, Serialize}; -use std::{ - fs::{self, File, OpenOptions}, - io::{ErrorKind, Write}, - path::{Path, PathBuf}, -}; - -#[cfg(unix)] -const PRIVATE_DIRECTORY_MODE: u32 = 0o700; -#[cfg(unix)] -const PRIVATE_FILE_MODE: u32 = 0o600; - -pub struct FileStorage { - path: PathBuf, - _lock: File, -} - -impl FileStorage { - pub fn lock(path: &Path) -> ResultType { - let parent = path - .parent() - .ok_or_else(|| crate::anyhow::anyhow!("Missing credential directory"))?; - let mut directories = fs::DirBuilder::new(); - directories.recursive(true); - #[cfg(unix)] - { - use std::os::unix::fs::DirBuilderExt; - directories.mode(PRIVATE_DIRECTORY_MODE); - } - directories - .create(parent) - .context("Create trusted-device credential directory")?; - let lock = lock_file(&path.with_extension("lock"))?; - Ok(Self { - path: path.to_owned(), - _lock: lock, - }) - } - - pub fn read(&self) -> ResultType { - match File::open(&self.path) { - Ok(file) => serde_json::from_reader(file).context("Read trusted-device credentials"), - Err(error) if error.kind() == ErrorKind::NotFound => Ok(T::default()), - Err(error) => Err(error).context("Open trusted-device credentials"), - } - } - - pub fn read_toml(&self) -> ResultType { - match fs::read_to_string(&self.path) { - Ok(value) => crate::toml::from_str(&value) - .map_err(|_| crate::anyhow::anyhow!("Invalid configuration file")), - Err(error) if error.kind() == ErrorKind::NotFound => Ok(T::default()), - Err(error) => Err(error).context("Open configuration file"), - } - } - - pub fn write_toml(&self, value: &T) -> ResultType<()> { - let value = crate::toml::to_string(value).context("Encode configuration update")?; - self.write_with(|file| Ok(file.write_all(value.as_bytes())?)) - } - - pub fn write(&self, value: &T) -> ResultType<()> { - self.write_with(|file| { - serde_json::to_writer(file, value).context("Encode trusted-device credential update") - }) - } - - fn write_with(&self, write: impl FnOnce(&mut File) -> ResultType<()>) -> ResultType<()> { - let temporary = self - .path - .with_extension(format!("{}.tmp", crate::uuid::Uuid::new_v4())); - let mut options = OpenOptions::new(); - options.write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(PRIVATE_FILE_MODE); - } - let mut file = options - .open(&temporary) - .context("Create trusted-device credential update")?; - write(&mut file)?; - file.sync_all() - .context("Persist trusted-device credential update")?; - #[cfg(not(windows))] - fs::rename(&temporary, &self.path).context("Commit trusted-device credential update")?; - #[cfg(windows)] - replace_file(&temporary, &self.path)?; - #[cfg(unix)] - if let Some(parent) = self.path.parent() { - File::open(parent)? - .sync_all() - .context("Persist trusted-device credential directory")?; - } - Ok(()) - } -} - -fn lock_file(path: &Path) -> ResultType { - let mut options = OpenOptions::new(); - options.read(true).write(true).create(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options - .mode(PRIVATE_FILE_MODE) - .custom_flags(crate::libc::O_NOFOLLOW | crate::libc::O_CLOEXEC); - } - #[cfg(windows)] - { - use std::os::windows::fs::OpenOptionsExt; - use windows::Win32::Storage::FileSystem::{FILE_SHARE_READ, FILE_SHARE_WRITE}; - options.share_mode(FILE_SHARE_READ.0 | FILE_SHARE_WRITE.0); - } - let file = options - .open(path) - .context("Lock trusted-device credentials")?; - #[cfg(unix)] - { - use std::os::fd::AsRawFd; - let result = unsafe { crate::libc::flock(file.as_raw_fd(), crate::libc::LOCK_EX) }; - if result != 0 { - return Err(std::io::Error::last_os_error()).context("Lock trusted-device credentials"); - } - } - #[cfg(windows)] - lock_windows_file(&file)?; - Ok(file) -} - -#[cfg(windows)] -fn lock_windows_file(file: &File) -> ResultType<()> { - use std::os::windows::io::AsRawHandle; - use windows::Win32::{Foundation::HANDLE, Storage::FileSystem, System::IO::OVERLAPPED}; - const LOCK_BYTES: u32 = 1; - // This is a synchronous handle: wait for the lock; closing the handle releases it. - unsafe { - FileSystem::LockFileEx( - HANDLE(file.as_raw_handle()), - FileSystem::LOCKFILE_EXCLUSIVE_LOCK, - None, - LOCK_BYTES, - 0, - &mut OVERLAPPED::default(), - ) - } - .context("Lock trusted-device credentials") -} - -#[cfg(windows)] -fn replace_file(source: &Path, destination: &Path) -> ResultType<()> { - use windows::{core::HSTRING, Win32::Storage::FileSystem}; - unsafe { - FileSystem::MoveFileExW( - &HSTRING::from(source), - &HSTRING::from(destination), - FileSystem::MOVEFILE_REPLACE_EXISTING | FileSystem::MOVEFILE_WRITE_THROUGH, - ) - } - .context("Commit trusted-device credential update") -} From c11a5971a30c78c7396686b2cac5c1e23c4bcf9f Mon Sep 17 00:00:00 2001 From: fufesou Date: Tue, 13 Oct 2026 18:48:53 -0700 Subject: [PATCH 03/11] fix: minimize trusted-device configuration save changes Signed-off-by: fufesou --- src/config.rs | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/src/config.rs b/src/config.rs index c6354099e..e2590bf8c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -517,14 +517,8 @@ impl Config2 { } fn store(&self) { - if let Err(error) = self.try_store() { - log::error!("Failed to store config2: {error}"); - } - } - - fn try_store(&self) -> crate::ResultType<()> { let mut config = self.clone(); - let stored: Config2 = try_load_path(Self::file())?; + let stored = Config::load_::("2"); // Ordinary settings must not restore grants from a stale snapshot. config.trusted_devices_v2 = stored.trusted_devices_v2; if let Some(mut socks) = config.socks { @@ -539,7 +533,7 @@ impl Config2 { } config.unlock_pin = keep_encrypted_storage_if_plaintext_unchanged(&config.unlock_pin, &stored.unlock_pin); - store_path(Self::file(), config) + Config::store_(&config, "2"); } pub fn get_trusted_devices_v2() -> crate::ResultType { @@ -1737,13 +1731,10 @@ impl PeerConfig { *v = encrypt_str_or_original(v, PASSWORD_ENC_VERSION, ENCRYPT_MAX_LEN) } } - let result = (|| { - let _lock = PEER_CONFIG_WRITE_LOCK.lock().unwrap(); - // A stale settings snapshot must not overwrite a newly issued credential. - config.trusted_device_v2 = try_load_path::(Self::path(id))?.trusted_device_v2; - store_path(Self::path(id), config) - })(); - if let Err(err) = result { + let _lock = PEER_CONFIG_WRITE_LOCK.lock().unwrap(); + // A stale settings snapshot must not overwrite a newly issued credential. + config.trusted_device_v2 = load_path::(Self::path(id)).trusted_device_v2; + if let Err(err) = store_path(Self::path(id), config) { log::error!("Failed to store config: {}", err); } NEW_STORED_PEER_CONFIG.lock().unwrap().insert(id.to_owned()); From dcc0381b7bbe0d044d691300c91ad856d5e27da2 Mon Sep 17 00:00:00 2001 From: fufesou Date: Wed, 14 Oct 2026 02:21:27 -0700 Subject: [PATCH 04/11] fix: preserve trusted credentials when configuration reads fail Stop ordinary Config2 and peer settings saves when the current file cannot be read. Keep first-save behavior for missing files and log failures without replacing V2 records with defaults. Signed-off-by: fufesou --- src/config.rs | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src/config.rs b/src/config.rs index e2590bf8c..d1c91b8bf 100644 --- a/src/config.rs +++ b/src/config.rs @@ -50,6 +50,7 @@ pub const READ_TIMEOUT: u64 = 18_000; pub const REG_INTERVAL: i64 = 15_000; pub const COMPRESS_LEVEL: i32 = 3; const SERIAL: i32 = 3; +const CONFIG_STORE_LOG_INTERVAL: Duration = Duration::from_secs(30); #[cfg(target_os = "macos")] lazy_static::lazy_static! { @@ -518,7 +519,18 @@ impl Config2 { fn store(&self) { let mut config = self.clone(); - let stored = Config::load_::("2"); + let stored: Self = match try_load_path(Self::file()) { + Ok(stored) => stored, + Err(err) => { + crate::throttled_log!( + CONFIG_STORE_LOG_INTERVAL, + error, + "Failed to read config2; skipping save: {}", + err + ); + return; + } + }; // Ordinary settings must not restore grants from a stale snapshot. config.trusted_devices_v2 = stored.trusted_devices_v2; if let Some(mut socks) = config.socks { @@ -1733,7 +1745,19 @@ impl PeerConfig { } let _lock = PEER_CONFIG_WRITE_LOCK.lock().unwrap(); // A stale settings snapshot must not overwrite a newly issued credential. - config.trusted_device_v2 = load_path::(Self::path(id)).trusted_device_v2; + config.trusted_device_v2 = match try_load_path::(Self::path(id)) { + Ok(stored) => stored.trusted_device_v2, + Err(err) => { + crate::throttled_log!( + CONFIG_STORE_LOG_INTERVAL, + error, + "Failed to read peer config '{}'; skipping save: {}", + id, + err + ); + return; + } + }; if let Err(err) = store_path(Self::path(id), config) { log::error!("Failed to store config: {}", err); } From 2289227c5fb5e705f35adb1b3becc4b865bc6abb Mon Sep 17 00:00:00 2001 From: fufesou Date: Fri, 16 Oct 2026 05:21:07 -0700 Subject: [PATCH 05/11] fix: preserve legacy trust data and validate V2 storage Retain legacy trusted-device records for migration without using them for authentication. Preserve malformed V2 values for strict validation while allowing explicit revocation to replace them. Signed-off-by: fufesou --- src/config.rs | 41 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/src/config.rs b/src/config.rs index d1c91b8bf..b82b2a296 100644 --- a/src/config.rs +++ b/src/config.rs @@ -245,12 +245,15 @@ pub struct Config2 { serial: i32, #[serde(default, deserialize_with = "deserialize_string")] unlock_pin: String, + // Deprecated: retained for migration only, never used for authentication. #[serde( default, deserialize_with = "deserialize_string", skip_serializing_if = "String::is_empty" )] - trusted_devices_v2: String, + trusted_devices: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + trusted_devices_v2: Option, #[serde(default)] socks: Option, @@ -519,7 +522,10 @@ impl Config2 { fn store(&self) { let mut config = self.clone(); - let stored: Self = match try_load_path(Self::file()) { + let stored = match try_load_path(Self::file()).and_then(|stored: Self| { + stored.trusted_devices_v2()?; + Ok(stored) + }) { Ok(stored) => stored, Err(err) => { crate::throttled_log!( @@ -533,6 +539,7 @@ impl Config2 { }; // Ordinary settings must not restore grants from a stale snapshot. config.trusted_devices_v2 = stored.trusted_devices_v2; + config.trusted_devices = stored.trusted_devices; if let Some(mut socks) = config.socks { let stored_password = stored .socks @@ -551,19 +558,43 @@ impl Config2 { pub fn get_trusted_devices_v2() -> crate::ResultType { let _lock = CONFIG2.read().unwrap(); let config: Self = try_load_path(Self::file())?; - Ok(config.trusted_devices_v2) + config.trusted_devices_v2().map(str::to_owned) + } + + pub fn has_trusted_devices_v2() -> crate::ResultType { + let _lock = CONFIG2.read().unwrap(); + let config: Self = try_load_path(Self::file())?; + // Explicit revocation must also replace malformed grant fields. + Ok(config + .trusted_devices_v2 + .as_ref() + .is_some_and(|value| value.as_str() != Some(""))) + } + + pub fn has_legacy_trusted_devices() -> crate::ResultType { + let _lock = CONFIG2.read().unwrap(); + let config: Self = try_load_path(Self::file())?; + Ok(!config.trusted_devices.is_empty()) + } + + fn trusted_devices_v2(&self) -> crate::ResultType<&str> { + match &self.trusted_devices_v2 { + None => Ok(""), + Some(toml::Value::String(value)) => Ok(value), + Some(_) => Err(anyhow!("Invalid trusted-device grants field")), + } } pub fn set_trusted_devices_v2(value: String) -> crate::ResultType<()> { let _lock = CONFIG2.write().unwrap(); let mut config: Self = try_load_path(Self::file())?; - config.trusted_devices_v2 = value; + config.trusted_devices_v2 = (!value.is_empty()).then(|| toml::Value::String(value)); store_path(Self::file(), config) } pub fn without_trusted_devices_v2(self) -> Self { Self { - trusted_devices_v2: String::new(), + trusted_devices_v2: None, ..self } } From e2b17fd06cbc7939662a2dfc112cfcac3ba5576e Mon Sep 17 00:00:00 2001 From: fufesou Date: Mon, 19 Oct 2026 01:21:02 -0700 Subject: [PATCH 06/11] fix: recover config saves while preserving valid legacy trust Signed-off-by: fufesou --- src/config.rs | 45 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/src/config.rs b/src/config.rs index b82b2a296..105675a9f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -522,11 +522,18 @@ impl Config2 { fn store(&self) { let mut config = self.clone(); - let stored = match try_load_path(Self::file()).and_then(|stored: Self| { - stored.trusted_devices_v2()?; - Ok(stored) - }) { - Ok(stored) => stored, + let stored = match try_load_path_for_store::(Self::file()) { + Ok(mut stored) => { + if stored.trusted_devices_v2().is_err() { + crate::throttled_log!( + CONFIG_STORE_LOG_INTERVAL, + warn, + "Invalid trusted-device grants field; saving settings without V2 trust credentials" + ); + stored.trusted_devices_v2 = None; + } + stored + } Err(err) => { crate::throttled_log!( CONFIG_STORE_LOG_INTERVAL, @@ -637,6 +644,32 @@ fn try_load_path( } } +fn try_load_path_for_store( + path: PathBuf, +) -> crate::ResultType { + match confy::load_path(path) { + Ok(config) => Ok(config), + Err(error) + if matches!(&error, confy::ConfyError::BadTomlData(_)) + || matches!(&error, confy::ConfyError::ReadConfigurationFileError(error) + if error.kind() == std::io::ErrorKind::InvalidData) => + { + crate::throttled_log!( + CONFIG_STORE_LOG_INTERVAL, + warn, + "Invalid configuration file; saving settings without trust credentials" + ); + Ok(T::default()) + } + Err(confy::ConfyError::GeneralLoadError(error)) + if error.kind() == std::io::ErrorKind::NotFound => + { + Ok(T::default()) + } + Err(error) => Err(error.into()), + } +} + pub fn load_path( file: PathBuf, ) -> T { @@ -1776,7 +1809,7 @@ impl PeerConfig { } let _lock = PEER_CONFIG_WRITE_LOCK.lock().unwrap(); // A stale settings snapshot must not overwrite a newly issued credential. - config.trusted_device_v2 = match try_load_path::(Self::path(id)) { + config.trusted_device_v2 = match try_load_path_for_store::(Self::path(id)) { Ok(stored) => stored.trusted_device_v2, Err(err) => { crate::throttled_log!( From 040bf3f662ae7422f2f9570701cc8451f7bb1d59 Mon Sep 17 00:00:00 2001 From: fufesou Date: Tue, 20 Oct 2026 16:11:45 +0800 Subject: [PATCH 07/11] refactor: remove unused legacy trusted-device detector The V2 management UI no longer displays legacy enrollment metadata. Remove the unused presence helper while preserving legacy records during ordinary saves. Signed-off-by: fufesou --- src/config.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/config.rs b/src/config.rs index 105675a9f..25d25b269 100644 --- a/src/config.rs +++ b/src/config.rs @@ -578,12 +578,6 @@ impl Config2 { .is_some_and(|value| value.as_str() != Some(""))) } - pub fn has_legacy_trusted_devices() -> crate::ResultType { - let _lock = CONFIG2.read().unwrap(); - let config: Self = try_load_path(Self::file())?; - Ok(!config.trusted_devices.is_empty()) - } - fn trusted_devices_v2(&self) -> crate::ResultType<&str> { match &self.trusted_devices_v2 { None => Ok(""), From 77f924d7a3a262007bc945660677c2bd1ba89f79 Mon Sep 17 00:00:00 2001 From: fufesou Date: Tue, 20 Oct 2026 23:24:04 +0800 Subject: [PATCH 08/11] fix: support atomic legacy trusted-device migration Signed-off-by: fufesou --- src/config.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/config.rs b/src/config.rs index 25d25b269..71563b911 100644 --- a/src/config.rs +++ b/src/config.rs @@ -245,7 +245,7 @@ pub struct Config2 { serial: i32, #[serde(default, deserialize_with = "deserialize_string")] unlock_pin: String, - // Deprecated: retained for migration only, never used for authentication. + // Imported by clients that support legacy trusted-device compatibility. #[serde( default, deserialize_with = "deserialize_string", @@ -563,9 +563,13 @@ impl Config2 { } pub fn get_trusted_devices_v2() -> crate::ResultType { + Self::get_trusted_device_stores().map(|(current, _)| current) + } + + pub fn get_trusted_device_stores() -> crate::ResultType<(String, String)> { let _lock = CONFIG2.read().unwrap(); let config: Self = try_load_path(Self::file())?; - config.trusted_devices_v2().map(str::to_owned) + Ok((config.trusted_devices_v2()?.to_owned(), config.trusted_devices)) } pub fn has_trusted_devices_v2() -> crate::ResultType { @@ -590,6 +594,7 @@ impl Config2 { let _lock = CONFIG2.write().unwrap(); let mut config: Self = try_load_path(Self::file())?; config.trusted_devices_v2 = (!value.is_empty()).then(|| toml::Value::String(value)); + config.trusted_devices.clear(); store_path(Self::file(), config) } From 41d50c40523aead6080cf1b1dbf52421cf01a585 Mon Sep 17 00:00:00 2001 From: fufesou Date: Wed, 21 Oct 2026 23:07:40 +0800 Subject: [PATCH 09/11] Remove unused trusted-device import stripping helper Signed-off-by: fufesou --- src/config.rs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/config.rs b/src/config.rs index 71563b911..acadc1029 100644 --- a/src/config.rs +++ b/src/config.rs @@ -598,13 +598,6 @@ impl Config2 { store_path(Self::file(), config) } - pub fn without_trusted_devices_v2(self) -> Self { - Self { - trusted_devices_v2: None, - ..self - } - } - pub fn get() -> Config2 { return CONFIG2.read().unwrap().clone(); } From cef0aedf407f3d67cb4567c4182e0ba606b8f145 Mon Sep 17 00:00:00 2001 From: fufesou Date: Thu, 22 Oct 2026 16:25:27 +0800 Subject: [PATCH 10/11] Keep trusted-device credentials in configuration sync snapshots Refresh cached trust fields after successful credential writes and provide explicit persisted credential synchronization. Ordinary settings saves continue to preserve the destination credentials. Signed-off-by: fufesou --- src/config.rs | 39 ++++++++++++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/src/config.rs b/src/config.rs index acadc1029..638ee0037 100644 --- a/src/config.rs +++ b/src/config.rs @@ -591,11 +591,40 @@ impl Config2 { } pub fn set_trusted_devices_v2(value: String) -> crate::ResultType<()> { - let _lock = CONFIG2.write().unwrap(); - let mut config: Self = try_load_path(Self::file())?; - config.trusted_devices_v2 = (!value.is_empty()).then(|| toml::Value::String(value)); - config.trusted_devices.clear(); - store_path(Self::file(), config) + Self { + trusted_devices_v2: (!value.is_empty()).then(|| toml::Value::String(value)), + ..Default::default() + } + .sync_trusted_devices() + } + + pub fn sync_trusted_devices(&self) -> crate::ResultType<()> { + self.trusted_devices_v2()?; + let mut current = CONFIG2.write().unwrap(); + let mut stored: Self = try_load_path(Self::file())?; + if stored.trusted_devices != self.trusted_devices + || stored.trusted_devices_v2 != self.trusted_devices_v2 + { + stored.trusted_devices.clone_from(&self.trusted_devices); + stored + .trusted_devices_v2 + .clone_from(&self.trusted_devices_v2); + store_path(Self::file(), &stored)?; + } + current.trusted_devices = stored.trusted_devices; + current.trusted_devices_v2 = stored.trusted_devices_v2; + Ok(()) + } + + pub fn get_for_sync() -> crate::ResultType { + let current = CONFIG2.read().unwrap(); + // The login-screen server can share this file with the system service. + let stored: Self = try_load_path(Self::file())?; + Ok(Self { + trusted_devices: stored.trusted_devices, + trusted_devices_v2: stored.trusted_devices_v2, + ..current.clone() + }) } pub fn get() -> Config2 { From 3ee3afd4389cd8885cc2a3e2def5272c24c80598 Mon Sep 17 00:00:00 2001 From: fufesou Date: Mon, 26 Oct 2026 15:22:00 +0800 Subject: [PATCH 11/11] Serialize peer deletion with credential writes Signed-off-by: fufesou --- src/config.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/config.rs b/src/config.rs index 46267b6ec..9ee5cacde 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1868,6 +1868,7 @@ impl PeerConfig { } pub fn remove(id: &str) { + let _lock = PEER_CONFIG_WRITE_LOCK.lock().unwrap(); fs::remove_file(Self::path(id)).ok(); }