Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(agent): validate the thread id in snapshot refs and fork index keys
James Damc64e81febae3
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rsindex c8aed9116..7fcd6f55f 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs@@ -668,6 +668,18 @@ async fn sweep_workspaces_in(dir: PathBuf, keep: &[String]) -> Result<usize, StrOk(removed)}+/// Names Windows maps to a device in every directory, in any case and also+/// with an extension (`nul.txt`). Checked on every OS so an id accepted on one+/// works on all of them.+fn is_windows_device_name(name: &str) -> bool {+ let stem = name.split('.').next().unwrap_or(name).to_ascii_uppercase();+ match stem.as_bytes() {+ [a, b, c] => matches!(&[*a, *b, *c], b"CON" | b"PRN" | b"AUX" | b"NUL"),+ [a, b, c, d] => matches!(&[*a, *b, *c], b"COM" | b"LPT") && d.is_ascii_digit(),+ _ => false,+ }+}+/// Sanitize a caller-supplied thread id into one safe path segment.////// Stricter than [`workspace_filename`] on purpose: a thread id is generated,@@ -681,7 +693,8 @@ pub fn thread_segment(thread_id: &str) -> Result<String, String> {&& id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))- && !id.chars().all(|c| c == '.');+ && !id.chars().all(|c| c == '.')+ && !is_windows_device_name(id);if !ok {return Err(format!("ERROR: invalid thread id '{thread_id}'"));}@@ -870,6 +883,13 @@ mod tests {"expected {bad:?} to be rejected");}+ // Windows device names, in any case and with an extension.+ for bad in ["CON", "nul", "Aux", "com1", "LPT9", "nul.txt", "CON.tar.gz"] {+ assert!(+ thread_segment(bad).is_err(),+ "expected {bad:?} to be rejected"+ );+ }assert!(thread_segment(&"a".repeat(129)).is_err(), "over-long id");}@@ -880,6 +900,9 @@ mod tests {"3f2a9c1e-1234-4c9a-9b7e-000000000000","thread_42","v1.2",+ "CONSOLE",+ "COM10",+ "con_1.x",] {assert_eq!(thread_segment(ok).unwrap(), ok);}diff --git a/src-tauri/src/core/agent/git.rs b/src-tauri/src/core/agent/git.rsindex 334fef30d..67e88e5a9 100644--- a/src-tauri/src/core/agent/git.rs+++ b/src-tauri/src/core/agent/git.rs@@ -90,18 +90,35 @@ fn temp_index() -> PathBuf {/// prior stat cache instead of a fresh empty one, so unchanged files are only/// stat'd (cheap) rather than re-hashed and re-inserted like every other file/// touched this turn. The id goes into a file name, so it must pass-/// [`validate_thread_id`](crate::core::threads::utils::validate_thread_id).+/// [`validate_index_key`].#[cfg(feature = "cli")]fn snapshot_index(thread_id: &str) -> Result<PathBuf, String> {- crate::core::threads::utils::validate_thread_id(thread_id)?;+ validate_index_key(thread_id)?;Ok(std::env::temp_dir().join(format!("jan-agent-snap-idx-{thread_id}")))}+/// Prefix of the one-shot index key a fork uses for its source thread.+#[cfg(feature = "cli")]+pub(crate) const FORK_BASE_KEY_PREFIX: &str = "fork-base-";++/// A snapshot index key is a thread id, or [`FORK_BASE_KEY_PREFIX`] followed+/// by one. The id part must pass+/// [`validate_thread_id`](crate::core::threads::utils::validate_thread_id), so+/// the prefix does not count against its length limit.+#[cfg(feature = "cli")]+fn validate_index_key(key: &str) -> Result<(), String> {+ let id = key.strip_prefix(FORK_BASE_KEY_PREFIX).unwrap_or(key);+ crate::core::threads::utils::validate_thread_id(id)+}+/// Hidden ref that keeps a thread's snapshot chain reachable across GC. One ref/// per thread; each snapshot parents the previous, so the whole chain is live.+/// The id goes into a ref name, so it must pass+/// [`validate_thread_id`](crate::core::threads::utils::validate_thread_id).#[cfg(feature = "cli")]-pub(crate) fn snapshot_ref(thread_id: &str) -> String {- format!("refs/jan/agent/snapshots/{thread_id}")+pub(crate) fn snapshot_ref(thread_id: &str) -> Result<String, String> {+ crate::core::threads::utils::validate_thread_id(thread_id)?;+ Ok(format!("refs/jan/agent/snapshots/{thread_id}"))}/// True when git tracks any file under `path` (a directory in a work tree).@@ -228,7 +245,7 @@ pub(crate) fn cleanup_snapshot_index(thread_id: &str) {/// Point the thread's snapshot ref at `sha` (create or update).#[cfg(feature = "cli")]pub(crate) fn update_ref(repo: &Path, thread_id: &str, sha: &str) -> Result<(), String> {- run(repo, None, &["update-ref", &snapshot_ref(thread_id), sha]).map(|_| ())+ run(repo, None, &["update-ref", &snapshot_ref(thread_id)?, sha]).map(|_| ())}/// Restore the working tree to snapshot `target`, discarding changes made after@@ -555,6 +572,26 @@ mod tests {assert_eq!(idx.parent(), Some(std::env::temp_dir().as_path()));// A rejected id fails the snapshot instead of writing elsewhere.assert!(snapshot(Path::new("."), None, "m", "../x", &[]).is_err());+ // The fork-base prefix does not count against the id's length limit,+ // but the id after it is still checked.+ let long_id = "a".repeat(128);+ assert!(snapshot_index(&format!("{FORK_BASE_KEY_PREFIX}{long_id}")).is_ok());+ assert!(snapshot_index(&format!("{FORK_BASE_KEY_PREFIX}../x")).is_err());+ assert!(snapshot_index(FORK_BASE_KEY_PREFIX).is_err());+ }++ #[test]+ fn snapshot_ref_rejects_ids_that_are_not_a_plain_name() {+ for bad in ["", "../x", "a/b", "a..b", "a b", "x^{tree}", "a:b", "nul"] {+ assert!(snapshot_ref(bad).is_err(), "{bad:?} should be rejected");+ }+ assert_eq!(+ snapshot_ref("0f8c2a3e-1b2c-4d5e-8f90-123456789abc").unwrap(),+ "refs/jan/agent/snapshots/0f8c2a3e-1b2c-4d5e-8f90-123456789abc"+ );+ let Some(root) = init_repo() else { return };+ assert!(update_ref(&root, "../../heads/main", "HEAD").is_err());+ let _ = std::fs::remove_dir_all(&root);}#[test]diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 3c6ae320e..1c896b0a6 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -1668,7 +1668,9 @@ fn fork_base(source: Option<&serde_json::Value>) -> Option<String> {}// Keyed per source thread and cleaned up: this index is a one-shot, unlike// the per-thread one a session keeps warm across its turns.- let key = format!("fork-base-{}", source.get("id")?.as_str()?);+ let source_id = source.get("id")?.as_str()?;+ crate::core::threads::utils::validate_thread_id(source_id).ok()?;+ let key = format!("{}{source_id}", git::FORK_BASE_KEY_PREFIX);let changed: Vec<PathBuf> = git::changed_paths(&workspace.path).into_iter().map(PathBuf::from)@@ -5122,6 +5124,16 @@ mod tests {"untracked files the agent created are carried too");+ // The source id names a temp file, so it must be a valid thread id; the+ // `fork-base-` prefix does not count against the id's length limit.+ let with_id = |id: &str| {+ let mut s = source.clone();+ s["id"] = serde_json::json!(id);+ s+ };+ assert_eq!(fork_base(Some(&with_id("../escape"))), None);+ assert!(fork_base(Some(&with_id(&"a".repeat(128)))).is_some());+// A recorded checkout the user deleted leaves the choice to HEAD.std::fs::remove_dir_all(&wt).unwrap();assert_eq!(fork_base(Some(&source)), None);diff --git a/src-tauri/src/core/threads/tests.rs b/src-tauri/src/core/threads/tests.rsindex 49f1c8efe..11571f0fc 100644--- a/src-tauri/src/core/threads/tests.rs+++ b/src-tauri/src/core/threads/tests.rs@@ -730,6 +730,9 @@ fn test_validate_thread_id_accepts_real_ids() {"01JABCDEFGHJKMNPQRSTVWXYZ0", // web-app ULID"temporary-chat","jan_1712345678",+ "CONSOLE",+ "COM10",+ "nul_thread",] {assert!(validate_thread_id(id).is_ok(), "{id} should be accepted");}@@ -751,6 +754,14 @@ fn test_validate_thread_id_rejects_path_like_ids() {"x\0y","with space","dot.ted",+ "CON",+ "nul",+ "Aux",+ "prn",+ "COM1",+ "com9",+ "LPT1",+ "lpt9",] {assert!(validate_thread_id(id).is_err(), "{id:?} should be rejected");assert!(get_thread_dir(std::path::Path::new("/tmp/jandata"), id).is_err());diff --git a/src-tauri/src/core/threads/utils.rs b/src-tauri/src/core/threads/utils.rsindex 013b4b1b6..b3ea257a0 100644--- a/src-tauri/src/core/threads/utils.rs+++ b/src-tauri/src/core/threads/utils.rs@@ -10,6 +10,18 @@ pub fn get_data_dir(data_folder: &Path) -> PathBuf {data_folder.join(THREADS_DIR)}+/// Names Windows maps to a device in every directory, in any case and also+/// with an extension (`nul.txt`). Checked on every OS so an id accepted on one+/// works on all of them.+fn is_windows_device_name(name: &str) -> bool {+ let stem = name.split('.').next().unwrap_or(name).to_ascii_uppercase();+ match stem.as_bytes() {+ [a, b, c] => matches!(&[*a, *b, *c], b"CON" | b"PRN" | b"AUX" | b"NUL"),+ [a, b, c, d] => matches!(&[*a, *b, *c], b"COM" | b"LPT") && d.is_ascii_digit(),+ _ => false,+ }+}+/// A thread id names a single directory under `threads/`, so it may only hold/// ASCII letters, digits, `-` and `_`. That covers every id Jan produces (UUIDs/// from the backend and the CLI, ULIDs from the web app, and fixed names such as@@ -25,6 +37,7 @@ pub fn validate_thread_id(thread_id: &str) -> Result<(), String> {if !thread_id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')+ || is_windows_device_name(thread_id){return Err(format!("Invalid thread id: {thread_id:?}"));}