Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(agent-tools): derive the data folder on the host and limit writable attaches

James Damc2d425d8d9f2
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
index eb3054ecd..1d1322ee5 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
@@ -99,10 +99,10 @@ fn with_renamed_shell_notices(
/// `project` is an explicit override and is currently always `None`: the desktop
/// has no project picker yet. Once one lands, a project's own store
/// (`~/.jan/projects/<slug>`) layers on top of this one; see the memory-scope TODO.
-fn resolve_store(data_folder: &str, project: Option<&str>) -> PathBuf {
+fn resolve_store(data_folder: &Path, project: Option<&str>) -> PathBuf {
match project.map(str::trim).filter(|p| !p.is_empty()) {
Some(p) => workspace::project_store(Path::new(p)),
- None => workspace::permanent_store(Path::new(data_folder)),
+ None => workspace::permanent_store(data_folder),
}
}
@@ -110,6 +110,7 @@ fn resolve_store(data_folder: &str, project: Option<&str>) -> PathBuf {
/// where memories and skills live.
#[tauri::command]
pub async fn workspace_path(data_folder: String) -> Result<String, AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
let root = workspace::ensure_permanent_store(Path::new(&data_folder)).await?;
Ok(root.to_string_lossy().to_string())
}
@@ -121,6 +122,7 @@ pub async fn thread_workspace_path(
data_folder: String,
thread_id: String,
) -> Result<String, AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
let dir = workspace::ensure_thread_workspace(Path::new(&data_folder), &thread_id).await?;
Ok(dir.to_string_lossy().to_string())
}
@@ -132,6 +134,7 @@ pub async fn thread_workspace_delete(
data_folder: String,
thread_id: String,
) -> Result<(), AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
workspace::remove_thread_workspace(Path::new(&data_folder), &thread_id)
.await
.map_err(Into::into)
@@ -151,6 +154,7 @@ pub async fn thread_workspace_sweep(
data_folder: String,
keep: Vec<String>,
) -> Result<usize, AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
workspace::sweep_stale_scratch_dirs().await;
workspace::sweep_thread_workspaces(Path::new(&data_folder), &keep)
.await
@@ -163,6 +167,7 @@ pub async fn session_workspace_path(
data_folder: String,
session_id: String,
) -> Result<String, AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
let dir = workspace::ensure_session_workspace(Path::new(&data_folder), &session_id).await?;
Ok(dir.to_string_lossy().to_string())
}
@@ -173,6 +178,7 @@ pub async fn session_workspace_delete(
data_folder: String,
session_id: String,
) -> Result<(), AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
workspace::remove_session_workspace(Path::new(&data_folder), &session_id)
.await
.map_err(Into::into)
@@ -188,6 +194,7 @@ pub async fn session_workspace_sweep(
data_folder: String,
keep: Vec<String>,
) -> Result<usize, AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
workspace::sweep_session_workspaces(Path::new(&data_folder), &keep)
.await
.map_err(Into::into)
@@ -200,6 +207,7 @@ pub async fn skill_list(
data_folder: String,
project: Option<String>,
) -> Result<Vec<SkillMeta>, AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
Ok(skills::list_meta(&resolve_store(
&data_folder,
project.as_deref(),
@@ -213,6 +221,7 @@ pub async fn skill_read(
project: Option<String>,
name: String,
) -> Result<String, AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
skills::read_raw(&resolve_store(&data_folder, project.as_deref()), &name).map_err(Into::into)
}
@@ -224,6 +233,7 @@ pub async fn skill_write(
name: String,
content: String,
) -> Result<(), AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
skills::write(
&resolve_store(&data_folder, project.as_deref()),
&name,
@@ -239,6 +249,7 @@ pub async fn skill_delete(
project: Option<String>,
name: String,
) -> Result<(), AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
skills::delete(&resolve_store(&data_folder, project.as_deref()), &name).map_err(Into::into)
}
/// Build a user prompt for an installed skill, including its body and arguments.
@@ -249,6 +260,7 @@ pub async fn skill_invoke(
name: String,
args: String,
) -> Result<String, AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
skills::build_invocation_message(
&resolve_store(&data_folder, project.as_deref()),
&name,
@@ -264,6 +276,7 @@ pub async fn memory_list(
data_folder: String,
project: Option<String>,
) -> Result<Vec<String>, AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
Ok(memory::list(&resolve_store(&data_folder, project.as_deref())).await)
}
@@ -273,6 +286,7 @@ pub async fn memory_read(
project: Option<String>,
name: String,
) -> Result<String, AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
memory::read(&resolve_store(&data_folder, project.as_deref()), &name)
.await
.map_err(Into::into)
@@ -285,6 +299,7 @@ pub async fn memory_write(
name: String,
content: String,
) -> Result<(), AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
memory::write(
&resolve_store(&data_folder, project.as_deref()),
&name,
@@ -303,6 +318,7 @@ pub async fn memory_catalog(
data_folder: String,
project: Option<String>,
) -> Result<Vec<memory::CatalogEntry>, AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
let store = resolve_store(&data_folder, project.as_deref());
// `catalog` is sync std::fs by design (the CLI calls it from sync context);
// keep its directory walk off the async runtime's thread here.
@@ -318,6 +334,7 @@ pub async fn memory_delete(
project: Option<String>,
name: String,
) -> Result<(), AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
memory::delete(&resolve_store(&data_folder, project.as_deref()), &name)
.await
.map_err(Into::into)
@@ -515,6 +532,7 @@ pub async fn attachment_import(
source: String,
text: Option<String>,
) -> Result<ImportedAttachment, AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
let workspace =
workspace::ensure_session_workspace(Path::new(&data_folder), &session_id).await?;
let imported = tokio::task::spawn_blocking(move || {
@@ -572,6 +590,7 @@ pub async fn start_monitor(
scope: Option<WorkspaceScope>,
on_update: tauri::ipc::Channel<crate::tools::monitor::MonitorUpdate>,
) -> Result<String, AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
use crate::tools::monitor;
if !jail::backend().enforces() {
return Err(AgentToolsError::from(
@@ -585,16 +604,14 @@ pub async fn start_monitor(
.ensure(Path::new(&data_folder), &thread_id)
.await?;
let scratch = workspace::ensure_scratch_dir(&thread_id).await?;
- let attached: Vec<PathBuf> = match read_only_project.as_deref() {
- Some(path) => vec![workspace::validate_read_root(
- Path::new(path),
- &sandbox,
- Some(Path::new(&data_folder)),
- )?],
- None => Vec::new(),
- };
- let (root, read_roots, write_roots) =
- resolve_workspace_root(sandbox, attached, project_writable.unwrap_or(false));
+ let writable = project_writable.unwrap_or(false);
+ let attached = attach_folder(
+ read_only_project.as_deref(),
+ &sandbox,
+ &data_folder,
+ writable,
+ )?;
+ let (root, read_roots, write_roots) = resolve_workspace_root(sandbox, attached, writable);
let ctx = monitor::MonitorCtx {
project_root: root,
scratch_root: Some(scratch),
@@ -697,6 +714,26 @@ pub async fn cancel_thread_bash(thread_id: String) -> Result<(), AgentToolsError
Ok(())
}
+/// Validate the folder a surface asked to attach (Cowork's shared folder, chat's
+/// read-only attachment): plural from the outset so attaching a second folder
+/// later is not another signature change. A writable attach must also pass
+/// [`workspace::validate_write_root`].
+fn attach_folder(
+ folder: Option<&str>,
+ sandbox: &Path,
+ data_folder: &Path,
+ writable: bool,
+) -> Result<Vec<PathBuf>, AgentToolsError> {
+ let Some(folder) = folder else {
+ return Ok(Vec::new());
+ };
+ let root = workspace::validate_read_root(Path::new(folder), sandbox, Some(data_folder))?;
+ if writable {
+ workspace::validate_write_root(&root, workspace::user_home().as_deref())?;
+ }
+ Ok(vec![root])
+}
+
/// Pick the workspace root a tool call resolves relative paths against, plus the
/// side roots it may read and write.
///
@@ -847,6 +884,7 @@ async fn execute_tool_inner(
call_id: Option<String>,
sink: Option<crate::tools::OutputSink>,
) -> Result<ToolResult, AgentToolsError> {
+ let data_folder = workspace::host_data_folder(&data_folder);
// Created here rather than trusted to exist: `escapes_project` canonicalizes
// the sandbox root and treats a missing one as an escape, so every tool call
// would be refused if the thread's first tool call arrived before any UI
@@ -870,21 +908,14 @@ async fn execute_tool_inner(
.map(PathBuf::from);
let skill_project: Option<PathBuf> =
project_dir.as_deref().map(workspace::project_store);
- // Plural from the outset so attaching a second folder later is not another
- // signature change.
- let attached: Vec<PathBuf> = match read_only_project.as_deref() {
- Some(path) => vec![workspace::validate_read_root(
- Path::new(path),
- &sandbox,
- Some(Path::new(&data_folder)),
- )?],
- None => Vec::new(),
- };
- let (root, read_roots, write_roots) = resolve_workspace_root(
- sandbox,
- attached,
- project_writable.unwrap_or(false),
- );
+ let writable = project_writable.unwrap_or(false);
+ let attached = attach_folder(
+ read_only_project.as_deref(),
+ &sandbox,
+ &data_folder,
+ writable,
+ )?;
+ let (root, read_roots, write_roots) = resolve_workspace_root(sandbox, attached, writable);
let tool = lookup(&name)
.ok_or_else(|| AgentToolsError::from(format!("unknown built-in tool '{name}'")))?;
// The desktop always sandboxes, and an attached project folder can be the
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs
index e9f08c809..c8aed9116 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs
@@ -310,6 +310,95 @@ pub fn validate_read_root(
Ok(canonical)
}
+/// Supplies the Jan data folder the host app is configured with.
+pub type DataFolderResolver = std::sync::Arc<dyn Fn() -> PathBuf + Send + Sync>;
+
+static DATA_FOLDER_RESOLVER: std::sync::OnceLock<DataFolderResolver> = std::sync::OnceLock::new();
+
+/// Install the process-wide data folder source. First call wins, like
+/// `hooks::set_resolver`, so nothing can swap it out later.
+pub fn set_data_folder_resolver(resolver: DataFolderResolver) {
+ let _ = DATA_FOLDER_RESOLVER.set(resolver);
+}
+
+/// The Jan data folder an IPC command works in.
+///
+/// The commands take a `data_folder` argument, but it only stands in for what
+/// the host already knows: everything containment rests on (the sandbox
+/// location, the mask over settings and keys, the store) is derived from it,
+/// so the host's value wins whenever one is installed. The argument is used
+/// as-is only without a host, as in this crate's tests.
+pub fn host_data_folder(requested: &str) -> PathBuf {
+ pick_data_folder(
+ DATA_FOLDER_RESOLVER.get().map(|resolve| resolve()),
+ requested,
+ )
+}
+
+fn pick_data_folder(host: Option<PathBuf>, requested: &str) -> PathBuf {
+ host.unwrap_or_else(|| PathBuf::from(requested))
+}
+
+/// Home-relative folders an agent must never be handed write access to:
+/// credentials, and the places that run code at login.
+const PROTECTED_HOME_DIRS: &[&str] = &[
+ ".ssh",
+ ".gnupg",
+ ".aws",
+ ".kube",
+ ".docker",
+ ".config/autostart",
+ ".config/systemd",
+ "Library/LaunchAgents",
+ "Library/Keychains",
+ "AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup",
+];
+
+/// The user's home directory, or `None` when unset or degenerate.
+pub fn user_home() -> Option<PathBuf> {
+ #[cfg(windows)]
+ let raw = std::env::var_os("USERPROFILE");
+ #[cfg(not(windows))]
+ let raw = std::env::var_os("HOME");
+ let home = PathBuf::from(raw?);
+ if home.parent().is_none() || home.as_os_str().is_empty() {
+ return None;
+ }
+ Some(home.canonicalize().unwrap_or(home))
+}
+
+/// Check that an attached folder (already through [`validate_read_root`]) may
+/// also be written.
+///
+/// Refused: the home directory itself or any folder above it, whose top level
+/// holds the shell rc files and profile scripts; and any folder inside, or
+/// containing, a [`PROTECTED_HOME_DIRS`] entry. A writable attach is the
+/// workspace root, writable by the file tools and the sandboxed shell alike, so
+/// these would hand the agent persistence or credentials.
+pub fn validate_write_root(root: &Path, home: Option<&Path>) -> Result<(), String> {
+ let Some(home) = home else {
+ return Ok(());
+ };
+ if is_within(home, root) {
+ return Err(format!(
+ "{} contains your home folder and cannot be attached writable; attach a project \
+ folder inside it instead",
+ root.display()
+ ));
+ }
+ for rel in PROTECTED_HOME_DIRS {
+ let protected = home.join(rel);
+ if is_within(root, &protected) || is_within(&protected, root) {
+ return Err(format!(
+ "{} overlaps {} and cannot be attached writable",
+ root.display(),
+ protected.display()
+ ));
+ }
+ }
+ Ok(())
+}
+
/// The session-scoped scratch directory: a subdirectory of the host temp dir
/// (e.g. `/tmp/jan-agent-<session>` on Linux), where `bash` scratch files
/// persist across calls for one session and the filesystem tools may write.
@@ -882,6 +971,66 @@ mod tests {
);
}
}
+ #[test]
+ fn host_data_folder_wins_over_the_requested_one() {
+ let host = PathBuf::from("/host/Jan/data");
+ assert_eq!(
+ pick_data_folder(Some(host.clone()), "/Users/x/Library/LaunchAgents"),
+ host
+ );
+ assert_eq!(pick_data_folder(Some(host.clone()), ""), host);
+ // No host installed (this crate's tests): the argument is all there is.
+ assert_eq!(
+ pick_data_folder(None, "/tmp/data"),
+ PathBuf::from("/tmp/data")
+ );
+ }
+
+ #[test]
+ fn validate_write_root_refuses_home_and_its_ancestors() {
+ let home = Path::new("/home/u");
+ assert!(validate_write_root(Path::new("/home/u"), Some(home)).is_err());
+ assert!(validate_write_root(Path::new("/home"), Some(home)).is_err());
+ }
+
+ #[test]
+ fn validate_write_root_refuses_protected_folders() {
+ let home = Path::new("/home/u");
+ for bad in [
+ "/home/u/.ssh",
+ "/home/u/.config",
+ "/home/u/.config/autostart",
+ "/home/u/.config/systemd/user",
+ "/home/u/Library",
+ "/home/u/Library/LaunchAgents",
+ "/home/u/Library/LaunchAgents/sub",
+ "/home/u/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup",
+ ] {
+ assert!(
+ validate_write_root(Path::new(bad), Some(home)).is_err(),
+ "{bad} should be refused"
+ );
+ }
+ }
+
+ #[test]
+ fn validate_write_root_accepts_a_project_folder() {
+ let home = Path::new("/home/u");
+ for ok in [
+ "/home/u/projects/site",
+ "/home/u/Documents/deck",
+ "/home/u/.configs-backup",
+ "/home/u/Library-notes",
+ "/srv/work",
+ ] {
+ assert!(
+ validate_write_root(Path::new(ok), Some(home)).is_ok(),
+ "{ok} should be accepted"
+ );
+ }
+ assert!(validate_write_root(Path::new("/home/u"), None).is_ok());
+ }
+
// Every rejection here is a case where the mount would not mean what the UI
// says it means, so each is refused rather than silently degraded.
#[test]
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 84338e80c..e37f5e254 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -356,6 +356,16 @@ pub fn run() {
mcp_last_known_tools: Arc::new(Mutex::new(HashMap::new())),
})
.setup(|app| {
+ // The agent-tools commands take a data folder from the webview; the
+ // sandbox, the mask over settings and keys, and the store all hang
+ // off it, so they use the configured one instead. Installed here,
+ // before the event loop delivers any IPC.
+ {
+ let handle = app.handle().clone();
+ tauri_plugin_agent_tools::workspace::set_data_folder_resolver(Arc::new(
+ move || get_jan_data_folder_path(handle.clone()),
+ ));
+ }
app.handle().plugin(
tauri_plugin_log::Builder::default()
.level(log::LevelFilter::Debug)