diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 8127cc53..1d1a0600 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1741,6 +1741,7 @@ dependencies = [ "security-framework", "serde", "serde_json", + "serde_path_to_error", "serial_test", "sha2 0.11.3", "shadowsocks", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 5c39d5dd..1a2c8829 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -34,6 +34,7 @@ resvg = { version = "0.50", default-features = false } [dependencies] serde_json = "1" serde = { version = "1", features = ["derive"] } +serde_path_to_error = "0.1" tauri = { version = "2", features = ["tray-icon", "image-png"] } tauri-plugin-opener = "2" tauri-plugin-fs = "2" diff --git a/src-tauri/src/api_server.rs b/src-tauri/src/api_server.rs index 6ef5472a..02fd7560 100644 --- a/src-tauri/src/api_server.rs +++ b/src-tauri/src/api_server.rs @@ -6293,16 +6293,26 @@ mod tests { #[test] fn malformed_wayfern_config_is_an_error_not_a_default() { - // `fingerprint` is a JSON-encoded string, so passing an object fails to - // parse. The handler must surface that as a 400: previously `.ok()` threw - // the whole config away, dropping the caller's `os` with it and returning - // a host-OS profile with 200 and no diagnostic. - let json = r#"{"os": "android", "fingerprint": {"platform": "Linux armv81"}}"#; - let value: serde_json::Value = serde_json::from_str(json).expect("value parses"); - let parsed = serde_json::from_value::(value); + // The handler must surface a config that does not parse as a 400: + // previously `.ok()` threw the whole config away, dropping the caller's + // `os` with it and returning a host-OS profile with 200 and no diagnostic. + let parse = |json: &str| { + serde_json::from_value::( + serde_json::from_str(json).expect("value parses"), + ) + }; assert!( - parsed.is_err(), - "an object fingerprint must not silently deserialize" + parse(r#"{"os": "android", "screen_max_width": "wide"}"#).is_err(), + "a malformed config must not silently deserialize" + ); + // A fingerprint sent as the object itself, not as its JSON text, is read + // as that text, and the `os` next to it stays. + let config = parse(r#"{"os": "android", "fingerprint": {"platform": "Linux armv81"}}"#) + .expect("an object fingerprint is read as its text"); + assert_eq!(config.os.as_deref(), Some("android")); + assert_eq!( + config.fingerprint.as_deref(), + Some(r#"{"platform":"Linux armv81"}"#) ); } diff --git a/src-tauri/src/profile/manager.rs b/src-tauri/src/profile/manager.rs index 18c57edf..b6d1790e 100644 --- a/src-tauri/src/profile/manager.rs +++ b/src-tauri/src/profile/manager.rs @@ -44,8 +44,18 @@ fn holds_profile(content: &str, expected: &BrowserProfile) -> Result String { + let mut deserializer = serde_json::Deserializer::from_str(content); + match serde_path_to_error::deserialize::<_, BrowserProfile>(&mut deserializer) { + Ok(_) => ".".to_string(), + Err(e) => e.path().to_string(), + } +} + /// `list_profiles` runs every few seconds, so a broken profile warns once per run. -fn warn_skipped_profile(dir: &Path, why: &str, err: &dyn std::fmt::Display) { +/// The field names the part of the file that failed, when it parsed as JSON. +fn warn_skipped_profile(dir: &Path, why: &str, field: Option<&str>, err: &dyn std::fmt::Display) { static WARNED: std::sync::Mutex>> = std::sync::Mutex::new(None); let first = WARNED @@ -62,9 +72,10 @@ fn warn_skipped_profile(dir: &Path, why: &str, err: &dyn std::fmt::Display) { } else { log::Level::Debug }; + let field = field.map(|f| format!(" field={f}")).unwrap_or_default(); log::log!( level, - "Profile skipped: {why} metadata.json profile={profile} err=\"{err}\"" + "Profile skipped: {why} metadata profile={profile}{field} err=\"{err}\"" ); } @@ -119,14 +130,15 @@ fn load_metadata(metadata_file: &Path) -> Option { let content = match fs::read_to_string(metadata_file) { Ok(c) => c, Err(e) => { - warn_skipped_profile(dir, "unreadable", &e); + warn_skipped_profile(dir, "unreadable", None, &e); return None; } }; let mut profile: BrowserProfile = match serde_json::from_str(&content) { Ok(p) => p, Err(e) => { - warn_skipped_profile(dir, "invalid", &e); + let field = invalid_field(&content); + warn_skipped_profile(dir, "invalid", Some(&field), &e); cache_metadata(metadata_file, stamp, None); return None; } @@ -1835,7 +1847,6 @@ impl ProfileManager { profile_id: &str, mut config: WayfernConfig, ) -> Result<(), Box> { - config.launch_args = crate::wayfern_manager::checked_launch_args(&config.launch_args).await?; // Find the profile by ID let profile_uuid = uuid::Uuid::parse_str(profile_id).map_err( |_| -> Box { @@ -1860,6 +1871,17 @@ impl ProfileManager { return Err(crate::backend_error("PROFILE_RUNNING").into()); } + // Only new arguments are checked. Arguments an older version stored, which + // the launch now leaves out, must not refuse a fingerprint edit. + let stored_args = profile + .wayfern_config + .as_ref() + .map(|c| c.launch_args.as_slice()) + .unwrap_or_default(); + if config.launch_args != stored_args { + config.launch_args = crate::wayfern_manager::checked_launch_args(&config.launch_args).await?; + } + let config = merge_submitted_wayfern_config(profile.wayfern_config.as_ref(), config); let stored = profile.wayfern_config.as_ref(); @@ -2456,6 +2478,33 @@ mod tests { assert!(!holds_profile(legacy, &changed).unwrap()); } + #[test] + fn a_hand_edited_file_still_loads_or_names_its_bad_field() { + let edited = r#"{ + "id": "7b0f7c9e-3f55-4c1b-9d7e-0f2f1f0c5a11", + "name": "Edited", + "browser": "wayfern", + "version": "158.0.8127.37", + "wayfern_config": { + "identity_id": "id-1", + "identity_overrides": { "brand": "Google Chrome" } + } + }"#; + let profile: BrowserProfile = serde_json::from_str(edited).unwrap(); + assert_eq!( + profile + .wayfern_config + .unwrap() + .identity_overrides + .as_deref(), + Some(r#"{"brand":"Google Chrome"}"#) + ); + + let broken = edited.replace(r#""identity_id": "id-1""#, r#""identity_id": 7"#); + assert!(serde_json::from_str::(&broken).is_err()); + assert_eq!(invalid_field(&broken), "wayfern_config.identity_id"); + } + fn create_test_profile_manager() -> (&'static ProfileManager, TempDir) { let temp_dir = TempDir::new().unwrap(); diff --git a/src-tauri/src/wayfern_manager.rs b/src-tauri/src/wayfern_manager.rs index 0dfcfad6..d77dc129 100644 --- a/src-tauri/src/wayfern_manager.rs +++ b/src-tauri/src/wayfern_manager.rs @@ -13,9 +13,29 @@ use tokio::process::Command as TokioCommand; use tokio::sync::Mutex as AsyncMutex; use tokio_tungstenite::{connect_async, tungstenite::Message}; +/// A field that holds a JSON object as text. Scripts and hand edits often +/// write the object itself; it is read as its text, so the profile still +/// loads. +fn json_text<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + Ok( + match Option::::deserialize(deserializer)? { + None | Some(serde_json::Value::Null) => None, + Some(serde_json::Value::String(text)) => Some(text), + Some(value) => Some(value.to_string()), + }, + ) +} + #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct WayfernConfig { - #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde( + default, + deserialize_with = "json_text", + skip_serializing_if = "Option::is_none" + )] pub fingerprint: Option, #[serde(default)] pub randomize_fingerprint_on_launch: Option, @@ -43,7 +63,7 @@ pub struct WayfernConfig { /// The user's edits to the profile's persona, as a JSON array of /// `{id,label,value}`. It holds only edits. An empty value removes that row /// from what the browser offers. - #[serde(default)] + #[serde(default, deserialize_with = "json_text")] pub persona: Option, /// A still (.png) or clip (.y4m/.mjpeg) the camera shows, as an absolute /// path. `None` means the computer's own camera. A file that is set is @@ -76,15 +96,19 @@ pub struct WayfernConfig { pub geo_proxy_signature: Option, #[serde(default)] pub identity_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde( + default, + deserialize_with = "json_text", + skip_serializing_if = "Option::is_none" + )] pub identity_baseline: Option, /// The user's own edits to the fingerprint, as a JSON object of fingerprint /// fields, sent as `setIdentity` overrides. `None` means no edits. - #[serde(default)] + #[serde(default, deserialize_with = "json_text")] pub identity_overrides: Option, /// The location of the profile's exit (timezone, timezoneOffset, language, /// languages, latitude, longitude, accuracy) as a JSON object. - #[serde(default)] + #[serde(default, deserialize_with = "json_text")] pub location: Option, } @@ -4420,6 +4444,41 @@ mod screen_tests { #[cfg(test)] mod tests { + #[test] + fn json_text_fields_read_an_object_as_its_text() { + let config: super::WayfernConfig = serde_json::from_value(serde_json::json!({ + "fingerprint": "{\"platform\":\"Win32\"}", + "identity_overrides": { "brand": "Google Chrome" }, + "location": { "timezone": "Europe/Paris" }, + "persona": [{ "id": "name", "label": "Name", "value": "A" }], + "identity_baseline": null, + })) + .unwrap(); + assert_eq!( + config.fingerprint.as_deref(), + Some(r#"{"platform":"Win32"}"#) + ); + assert_eq!( + config.identity_overrides.as_deref(), + Some(r#"{"brand":"Google Chrome"}"#) + ); + assert_eq!( + config.location.as_deref(), + Some(r#"{"timezone":"Europe/Paris"}"#) + ); + assert_eq!( + config.persona.as_deref(), + Some(r#"[{"id":"name","label":"Name","value":"A"}]"#) + ); + assert_eq!(config.identity_baseline, None); + assert_eq!( + serde_json::from_str::("{}") + .unwrap() + .identity_overrides, + None + ); + } + #[test] fn identity_location_carries_the_exit_for_create_identity() { let geo = crate::geolocation::Geolocation {