Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(threads): refuse create-writes over a foreign messages log
Akarshan Biswas20eb3366c4f8
diff --git a/src-tauri/src/core/threads/commands.rs b/src-tauri/src/core/threads/commands.rsindex 62d2a0e41..237611bb0 100644--- a/src-tauri/src/core/threads/commands.rs+++ b/src-tauri/src/core/threads/commands.rs@@ -123,6 +123,42 @@ fn thread_extra_path(Ok(get_thread_dir(data_folder, thread_id)?.join(format!("{name}.json")))}+/// Guard for the `create: true` writes that run before thread.json commits a+/// thread. `create_message` makes the directory too, so a directory can hold a+/// real chat log with no thread.json yet, and an uncommitted migration must not+/// overwrite it. A non-empty messages.jsonl is only treated as the migration's+/// own when a sidecar is already there (the migration writes the sidecar first,+/// so any retry after a crash finds it) or, for a messages write, when the file+/// is byte-identical to the batch about to be written. Absent or empty logs+/// belong to nobody. `incoming` is the exact messages.jsonl body being written,+/// or `None` for a sidecar write.+fn ensure_uncommitted_dir_is_ours(+ data_folder: &std::path::Path,+ thread_id: &str,+ incoming: Option<&[u8]>,+) -> Result<(), String> {+ if get_thread_metadata_path(data_folder, thread_id)?.exists() {+ return Ok(());+ }+ let log = get_messages_path(data_folder, thread_id)?;+ let existing = match fs::read(&log) {+ Ok(bytes) => bytes,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),+ Err(e) => return Err(e.to_string()),+ };+ if existing.is_empty() || incoming == Some(existing.as_slice()) {+ return Ok(());+ }+ for name in THREAD_EXTRA_NAMES {+ if thread_extra_path(data_folder, thread_id, name)?.exists() {+ return Ok(());+ }+ }+ Err(format!(+ "Thread '{thread_id}' has messages but no thread.json; refusing to overwrite its messages"+ ))+}+/// Reads a per-thread sidecar (for example the Cowork transcript)./// Returns `Ok(None)` when the sidecar does not exist.#[tauri::command]@@ -166,6 +202,7 @@ pub async fn write_thread_extra<R: Runtime>(let lock = get_lock_for_thread(&thread_id).await;let _guard = lock.lock().await;if create.unwrap_or(false) {+ ensure_uncommitted_dir_is_ours(&data_folder, &thread_id, None)?;ensure_thread_dir_exists(&data_folder, &thread_id)?;} else if !get_thread_metadata_path(&data_folder, &thread_id)?.exists() {return Err(format!(@@ -211,14 +248,20 @@ pub async fn replace_thread_messages<R: Runtime>(let path = get_messages_path(&data_folder, &thread_id)?;let lock = get_lock_for_thread(&thread_id).await;let _guard = lock.lock().await;+ let mut body = String::new();+ for message in &messages {+ body.push_str(&serde_json::to_string(message).map_err(|e| e.to_string())?);+ body.push('\n');+ }if create.unwrap_or(false) {+ ensure_uncommitted_dir_is_ours(&data_folder, &thread_id, Some(body.as_bytes()))?;ensure_thread_dir_exists(&data_folder, &thread_id)?;} else if !get_thread_metadata_path(&data_folder, &thread_id)?.exists() {return Err(format!("Thread '{thread_id}' has no thread.json; refusing to create it from a messages write"));}- write_messages_to_file(&messages, &path)+ write_atomic(&path, body.as_bytes())}/// Modifies an existing thread's metadata by overwriting its thread.json file.diff --git a/src-tauri/src/core/threads/tests.rs b/src-tauri/src/core/threads/tests.rsindex 694e99009..233e5eb3c 100644--- a/src-tauri/src/core/threads/tests.rs+++ b/src-tauri/src/core/threads/tests.rs@@ -1073,6 +1073,18 @@ async fn test_replace_thread_messages_replaces_instead_of_appending() {migrated_message("replace-thread", "replace-thread-msg-1", "two"),];+ // The migration writes the sidecar first, so a retry always finds it; that+ // marks a later uncommitted log as the migration's own.+ write_thread_extra(+ app.handle().clone(),+ "replace-thread".into(),+ "cowork".into(),+ json!({"turns": []}),+ Some(true),+ )+ .await+ .unwrap();+// The migration writes before thread.json exists, so it must be allowed to// create the directory.replace_thread_messages(@@ -1120,7 +1132,9 @@ async fn test_replace_thread_messages_replaces_instead_of_appending() {.unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();- assert_eq!(names, vec![MESSAGES_FILE.to_string()]);+ assert_eq!(names.len(), 2, "{names:?}");+ assert!(names.contains(&MESSAGES_FILE.to_string()));+ assert!(names.contains(&"cowork.json".to_string()));let threads = list_threads(app.handle().clone()).await.unwrap();assert!(threads.iter().all(|t| t["id"] != "replace-thread"));}@@ -1265,3 +1279,122 @@ async fn test_thread_extra_and_messages_roundtrip_non_representable_doubles() {assert_eq!(got.as_f64().unwrap().to_bits(), want.to_bits());}}++fn thread_dir_of(app: &tauri::App<MockRuntime>, id: &str) -> PathBuf {+ let data_folder = get_jan_data_folder_path(app.handle().clone());+ get_thread_dir(&data_folder, id).unwrap()+}++#[tokio::test]+async fn test_replace_thread_messages_create_refuses_a_foreign_log_without_thread_json() {+ let (app, _data_dir) = mock_app_with_temp_data_dir();+ // A chat message landed first (create_message makes the directory) but its+ // thread.json is not there: a migration must not overwrite that log.+ create_message(+ app.handle().clone(),+ create_test_message("clash-thread", "keep me"),+ )+ .await+ .unwrap();+ let path = get_messages_path(+ &get_jan_data_folder_path(app.handle().clone()),+ "clash-thread",+ )+ .unwrap();+ let before = fs::read(&path).unwrap();++ let batch = vec![migrated_message("clash-thread", "clash-thread-msg-0", "x")];+ let err = replace_thread_messages(+ app.handle().clone(),+ "clash-thread".into(),+ batch,+ Some(true),+ )+ .await+ .unwrap_err();+ assert!(err.contains("messages"), "{err}");+ assert_eq!(fs::read(&path).unwrap(), before);+}++#[tokio::test]+async fn test_replace_thread_messages_create_allows_the_migrations_own_retry() {+ let (app, _data_dir) = mock_app_with_temp_data_dir();+ let batch = vec![migrated_message("retry-thread", "retry-thread-msg-0", "x")];+ // First run crashed before thread.json: the log holds exactly this batch.+ replace_thread_messages(+ app.handle().clone(),+ "retry-thread".into(),+ batch.clone(),+ Some(true),+ )+ .await+ .unwrap();+ // The retry writes the same bytes again and is allowed.+ replace_thread_messages(+ app.handle().clone(),+ "retry-thread".into(),+ batch.clone(),+ Some(true),+ )+ .await+ .unwrap();+ // A different batch over that uncommitted log is not the same run.+ let other = vec![migrated_message("retry-thread", "retry-thread-msg-0", "y")];+ assert!(replace_thread_messages(+ app.handle().clone(),+ "retry-thread".into(),+ other,+ Some(true),+ )+ .await+ .is_err());+ // An empty leftover log is not anyone's data.+ let empty = thread_dir_of(&app, "empty-thread");+ fs::create_dir_all(&empty).unwrap();+ fs::write(empty.join(MESSAGES_FILE), "").unwrap();+ replace_thread_messages(+ app.handle().clone(),+ "empty-thread".into(),+ vec![migrated_message("empty-thread", "empty-thread-msg-0", "x")],+ Some(true),+ )+ .await+ .unwrap();+}++#[tokio::test]+async fn test_write_thread_extra_create_refuses_a_foreign_log_without_thread_json() {+ let (app, _data_dir) = mock_app_with_temp_data_dir();+ create_message(+ app.handle().clone(),+ create_test_message("extra-clash", "keep me"),+ )+ .await+ .unwrap();+ let dir = thread_dir_of(&app, "extra-clash");++ let err = write_thread_extra(+ app.handle().clone(),+ "extra-clash".into(),+ "cowork".into(),+ json!({"turns": []}),+ Some(true),+ )+ .await+ .unwrap_err();+ assert!(err.contains("messages"), "{err}");+ assert!(!dir.join("cowork.json").exists());++ // Once the migration's own sidecar is there, the retry after a crash that+ // came after the messages write is allowed to rewrite it.+ fs::write(dir.join("cowork.json"), "{}").unwrap();+ write_thread_extra(+ app.handle().clone(),+ "extra-clash".into(),+ "cowork".into(),+ json!({"turns": []}),+ Some(true),+ )+ .await+ .unwrap();+}