//! H4: a database never lives inside a synced folder. //! //! `~/Documents` and `~/Desktop` are iCloud Drive when *Desktop & Documents //! Folders* is on. The database and the media are plaintext on disk, so iCloud //! would upload them plaintext to Apple-held keys, would sync a live SQLite file //! the server holds open (a corruption path), and would invite a second Mac to //! open the same file — the one-server-per-data-directory hazard. Our own R2 //! backup is age-encrypted before it leaves the Mac; iCloud would be strictly //! worse. //! //! What macOS stamps on such a folder is the extended attribute //! `com.apple.file-provider-domain-id` (verified: `xattr -l ~/Documents` under //! Desktop & Documents Folders reads //! `com.apple.CloudDocs.iCloudDriveFileProvider/…`). Every third-party File //! Provider — Dropbox, Google Drive — stamps it too, which is why the check is //! on the attribute rather than on a list of folder names. //! //! The decision is PURE over `(path, home, read_attribute)`; the adapter below //! is the only part that touches the disk. use std::path::{Path, PathBuf}; #[cfg(target_os = "macos")] use std::process::Command; /// The attribute a File Provider stamps on the folder it manages. pub const FILE_PROVIDER_ATTRIBUTE: &str = "com.apple.file-provider-domain-id"; /// Why a path may not hold a database. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SyncedKind { /// Under `~/Library/Mobile Documents`. ICloudDrive, /// The folder, or one of its ancestors, carries the attribute. FileProvider, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct SyncedRefusal { pub kind: SyncedKind, /// The folder that is actually synced, which may be an ancestor of the data /// directory. pub path: PathBuf, /// The File Provider's domain, when that is what was found. pub domain: Option, } /// `None` when the path may hold a database, a refusal when it may not. /// /// The walk goes from the data directory upward and stops BEFORE `home`: the /// home folder's own attributes are not this app's business, and reading them /// would refuse every path on a Mac whose whole home is managed. pub fn synced_location_refusal( path: impl AsRef, home: impl AsRef, read_attribute: &dyn Fn(&Path) -> Option, ) -> Option { let path = path.as_ref(); let home = home.as_ref(); let mobile_documents = home.join("Library").join("Mobile Documents"); if path == mobile_documents || path.starts_with(&mobile_documents) { return Some(SyncedRefusal { kind: SyncedKind::ICloudDrive, path: path.to_path_buf(), domain: None, }); } let mut dir = path; loop { if dir == home { return None; } if let Some(domain) = read_attribute(dir) { if !domain.trim().is_empty() { return Some(SyncedRefusal { kind: SyncedKind::FileProvider, path: dir.to_path_buf(), domain: Some(domain), }); } } match dir.parent() { // `Path::parent()` of "/" is None, which is where the walk of a path // outside the home folder terminates — the TypeScript's `dirname` // returned "/" for "/" and compared, which is the same stop. Some(parent) if parent != dir => dir = parent, _ => return None, } } } /// The adapter: `/usr/bin/xattr -p`, which exits non-zero when the attribute is /// not set. Anything that is not a clean read is treated as "no attribute" — a /// folder the tool cannot describe is not evidence that it is synced. // File Provider and iCloud are Apple services; Linux has neither attribute. #[cfg(not(target_os = "macos"))] pub fn read_file_provider_attribute(_path: &Path) -> Option { None } #[cfg(target_os = "macos")] pub fn read_file_provider_attribute(path: &Path) -> Option { let run = Command::new("/usr/bin/xattr") .arg("-p") .arg(FILE_PROVIDER_ATTRIBUTE) .arg(path) .output() .ok()?; if !run.status.success() { return None; } let value = String::from_utf8_lossy(&run.stdout).trim().to_string(); if value.is_empty() { None } else { Some(value) } } /// What the person is shown. Plain words: folder, database, app. pub fn synced_refusal_message(refusal: &SyncedRefusal, data_dir: &Path) -> String { let why = match refusal.kind { SyncedKind::ICloudDrive => format!("{} is inside iCloud Drive.", refusal.path.display()), SyncedKind::FileProvider => format!( "{} is synced to the cloud ({} manages it).", refusal.path.display(), refusal.domain.as_deref().unwrap_or("a file provider") ), }; [ format!( "CottonDB keeps your database at {}, and it cannot run there.", data_dir.display() ), why, "A synced folder would upload your database and your files unencrypted, would copy a database the app has open, and would let a second Mac open the same file.".to_string(), "Move that folder out of the synced location, or point CottonDB somewhere else, and open the app again.".to_string(), ] .join("\n\n") } #[cfg(test)] mod tests { use super::*; use std::cell::RefCell; use std::collections::HashMap; const HOME: &str = "/Users/x"; /// What macOS stamps on a folder a File Provider manages. const DOMAIN: &str = "com.apple.CloudDocs.iCloudDriveFileProvider/x"; /// A reader that answers for the named paths and `None` everywhere else, /// recording what it was asked. struct Reader { stamped: HashMap, seen: RefCell>, } impl Reader { fn new(stamped: &[(&str, &str)]) -> Self { Self { stamped: stamped .iter() .map(|(p, v)| (PathBuf::from(p), v.to_string())) .collect(), seen: RefCell::new(Vec::new()), } } fn read(&self) -> impl Fn(&Path) -> Option + '_ { move |path: &Path| { self.seen.borrow_mut().push(path.to_path_buf()); self.stamped.get(path).cloned() } } fn seen(&self) -> Vec { self.seen.borrow().clone() } } #[test] fn it_allows_a_plain_folder_in_the_home_directory() { let reader = Reader::new(&[]); assert_eq!( synced_location_refusal("/Users/x/CottonDB", HOME, &reader.read()), None ); } #[test] fn it_refuses_anything_under_mobile_documents_attribute_or_not() { let reader = Reader::new(&[]); let path = "/Users/x/Library/Mobile Documents/com~apple~CloudDocs/CottonDB"; let refusal = synced_location_refusal(path, HOME, &reader.read()).expect("a refusal"); assert_eq!(refusal.kind, SyncedKind::ICloudDrive); assert_eq!(refusal.path, PathBuf::from(path)); } #[test] fn it_refuses_the_data_dir_itself_when_it_carries_the_attribute() { let reader = Reader::new(&[("/Users/x/CottonDB", DOMAIN)]); let refusal = synced_location_refusal("/Users/x/CottonDB", HOME, &reader.read()).expect("a refusal"); assert_eq!(refusal.kind, SyncedKind::FileProvider); assert_eq!(refusal.path, PathBuf::from("/Users/x/CottonDB")); } #[test] fn it_refuses_when_an_ancestor_carries_it_desktop_and_documents_stamps_the_parent() { let reader = Reader::new(&[("/Users/x/Documents", DOMAIN)]); let refusal = synced_location_refusal("/Users/x/Documents/CottonDB", HOME, &reader.read()) .expect("a refusal"); assert_eq!(refusal.kind, SyncedKind::FileProvider); // The refusal names the folder that is actually synced, not the leaf. assert_eq!(refusal.path, PathBuf::from("/Users/x/Documents")); assert_eq!(refusal.domain.as_deref(), Some(DOMAIN)); } #[test] fn it_never_reads_the_home_folder_itself_the_walk_stops_before_it() { let reader = Reader::new(&[(HOME, DOMAIN)]); assert_eq!( synced_location_refusal("/Users/x/a/b/CottonDB", HOME, &reader.read()), None ); assert_eq!( reader.seen(), vec![ PathBuf::from("/Users/x/a/b/CottonDB"), PathBuf::from("/Users/x/a/b"), PathBuf::from("/Users/x/a"), ] ); } #[test] fn it_terminates_on_a_path_outside_the_home_folder_rather_than_walking_for_ever() { let reader = Reader::new(&[]); assert_eq!( synced_location_refusal("/tmp/scratch/CottonDB", HOME, &reader.read()), None ); assert_eq!( reader.seen(), vec![ PathBuf::from("/tmp/scratch/CottonDB"), PathBuf::from("/tmp/scratch"), PathBuf::from("/tmp"), PathBuf::from("/"), ] ); } #[test] fn it_treats_an_empty_attribute_value_as_absent_xattr_prints_nothing_for_an_unset_key() { let reader = Reader::new(&[("/Users/x/CottonDB", "")]); assert_eq!( synced_location_refusal("/Users/x/CottonDB", HOME, &reader.read()), None ); } #[test] fn the_message_names_the_folder_the_database_and_what_to_do() { let refusal = SyncedRefusal { kind: SyncedKind::FileProvider, path: PathBuf::from("/Users/x/Documents"), domain: Some(DOMAIN.to_string()), }; let message = synced_refusal_message(&refusal, Path::new("/Users/x/Documents/CottonDB")); assert!(message.contains("/Users/x/Documents/CottonDB")); assert!(message.contains("synced to the cloud")); assert!(message.contains("open the app again.")); } }