Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(agent-tools): let a screenshot of a file outside the workspace load only that file
James Dam0161b65765b4
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/screenshot_pages.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/screenshot_pages.rsindex 2ff26b94d..cb2028372 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/screenshot_pages.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/screenshot_pages.rs@@ -5,7 +5,8 @@//! PNG would carry it back. The renderer records each window's target here//! before the window exists, and the app's navigation guard asks [`allows`]//! before a screenshot window loads a `file:` URL: only the target and files-//! under its directory (its own css, images, scripts) pass.+//! under its directory (its own css, images, scripts) pass, or the target alone+//! when it lies outside the agent's trusted roots ([`PageScope`]).//!//! Tauri-free: the renderer registers, the guard in the app crate reads.//!@@ -19,9 +20,21 @@ use std::sync::{Mutex, MutexGuard};/// guard.pub static SCREENSHOT_PAGES: ScreenshotPages = ScreenshotPages::new();+/// What a screenshot window may load besides its target.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PageScope {+ /// The files under the target's directory too: a page inside the agent's+ /// workspace, scratch or attached folders.+ Directory,+ /// The target alone: a page the user approved outside those roots, whose+ /// directory (`~/Desktop`, say) holds files nobody approved.+ FileOnly,+}+struct Page {target: PathBuf,- dir: PathBuf,+ /// `None` for [`PageScope::FileOnly`].+ dir: Option<PathBuf>,}pub struct ScreenshotPages {@@ -35,15 +48,21 @@ impl ScreenshotPages {}}- /// Lets the window labelled `label` load `target` and the files under its- /// directory, both as they resolve now.- pub fn register(&self, label: &str, target: &Path) -> Result<(), String> {+ /// Lets the window labelled `label` load `target`, and with+ /// [`PageScope::Directory`] the files under its directory, both as they+ /// resolve now.+ pub fn register(&self, label: &str, target: &Path, scope: PageScope) -> Result<(), String> {let target = std::fs::canonicalize(target).map_err(|e| format!("cannot resolve {}: {e}", target.display()))?;- let dir = target- .parent()- .ok_or_else(|| format!("{} has no parent directory", target.display()))?- .to_path_buf();+ let dir = match scope {+ PageScope::Directory => Some(+ target+ .parent()+ .ok_or_else(|| format!("{} has no parent directory", target.display()))?+ .to_path_buf(),+ ),+ PageScope::FileOnly => None,+ };self.lock().insert(label.to_string(), Page { target, dir });Ok(())}@@ -64,7 +83,9 @@ impl ScreenshotPages {}self.lock().get(label)- .is_some_and(|page| canon == page.target || canon.starts_with(&page.dir))+ .is_some_and(|page| {+ canon == page.target || page.dir.as_ref().is_some_and(|dir| canon.starts_with(dir))+ })}fn lock(&self) -> MutexGuard<'_, BTreeMap<String, Page>> {@@ -102,7 +123,9 @@ mod tests {let dir = temp_dir("in");let pages = ScreenshotPages::new();assert!(!pages.allows("jan-shot-1", &dir.join("chart.html")));- pages.register("jan-shot-1", &dir.join("chart.html")).unwrap();+ pages+ .register("jan-shot-1", &dir.join("chart.html"), PageScope::Directory)+ .unwrap();assert!(pages.allows("jan-shot-1", &dir.join("chart.html")));assert!(pages.allows("jan-shot-1", &dir.join("assets/style.css")));assert!(!pages.allows("jan-shot-2", &dir.join("chart.html")));@@ -112,12 +135,27 @@ mod tests {assert!(!pages.allows("jan-shot-1", &dir.join("chart.html")));}+ #[test]+ fn a_file_only_page_allows_the_target_and_nothing_beside_it() {+ let dir = temp_dir("file-only");+ std::fs::write(dir.join("notes.txt"), "private").unwrap();+ let pages = ScreenshotPages::new();+ pages+ .register("jan-shot-1", &dir.join("chart.html"), PageScope::FileOnly)+ .unwrap();+ assert!(pages.allows("jan-shot-1", &dir.join("chart.html")));+ assert!(!pages.allows("jan-shot-1", &dir.join("notes.txt")));+ assert!(!pages.allows("jan-shot-1", &dir.join("assets/style.css")));+ }+#[test]fn files_outside_the_target_directory_are_refused_however_spelled() {let dir = temp_dir("out");let other = temp_dir("other");let pages = ScreenshotPages::new();- pages.register("jan-shot-1", &dir.join("chart.html")).unwrap();+ pages+ .register("jan-shot-1", &dir.join("chart.html"), PageScope::Directory)+ .unwrap();assert!(!pages.allows("jan-shot-1", &other.join("chart.html")));let escape = dir.join("..")@@ -133,7 +171,9 @@ mod tests {let other = temp_dir("secret");std::os::unix::fs::symlink(other.join("chart.html"), dir.join("leak.html")).unwrap();let pages = ScreenshotPages::new();- pages.register("jan-shot-1", &dir.join("chart.html")).unwrap();+ pages+ .register("jan-shot-1", &dir.join("chart.html"), PageScope::Directory)+ .unwrap();assert!(!pages.allows("jan-shot-1", &dir.join("leak.html")));}@@ -141,7 +181,11 @@ mod tests {fn registering_a_missing_target_errors() {let pages = ScreenshotPages::new();assert!(pages- .register("jan-shot-1", Path::new("/definitely/not/here.html"))+ .register(+ "jan-shot-1",+ Path::new("/definitely/not/here.html"),+ PageScope::Directory+ ).is_err());}}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rsindex 828887804..9c3286724 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs@@ -18,6 +18,7 @@ use crate::tools::sandbox::{escapes_write_roots, hidden_under, in_scratch, landing, lexical_normalize,refuse_windows_name, resolve_path, scratch_display_path, symlink_escapes_any_root, Landing,};+use crate::screenshot_pages::PageScope;use crate::tools::{BuiltinTool, ImageContentPart, ScreenshotBackend, ToolContext};const MAX_BYTES: usize = 64 * 1024;@@ -1506,6 +1507,7 @@ pub async fn render_html_png(width: u64,height: u64,scale: f64,+ scope: PageScope,backend: Option<&ScreenshotBackend>,) -> Result<Vec<u8>, String> {let ext = target@@ -1534,7 +1536,7 @@ pub async fn render_html_png(// works without Chrome; on any failure fall through to Chrome so nothing// regresses.if let Some(backend) = backend {- match backend(target.to_path_buf(), width, height, scale).await {+ match backend(target.to_path_buf(), width, height, scale, scope).await {Ok(png) => return finalize_screenshot_png(png),Err(_) => { /* fall through to Chrome */ }}@@ -1670,13 +1672,21 @@ async fn screenshot(let width = arg_u64(args, "width").unwrap_or(1280).clamp(320, 4096);let height = arg_u64(args, "height").unwrap_or(960).clamp(240, 4096);let target = resolve_path(root, scratch, path);- if symlink_escapes_any_root(root, scratch, read_roots, &target) {- return (- format!("ERROR: refused to screenshot through a symlink out of the workspace: {path}"),- None,- );- }- let png = match render_html_png(&target, width, height, 1.0, backend).await {+ // A page the user approved outside the trusted roots gets no neighbours:+ // its directory was never part of what they approved.+ let scope = match landing(root, scratch, read_roots, &target) {+ Landing::Escapes => {+ return (+ format!(+ "ERROR: refused to screenshot through a symlink out of the workspace: {path}"+ ),+ None,+ );+ }+ Landing::Inside(_) => PageScope::Directory,+ Landing::Outside(_) => PageScope::FileOnly,+ };+ let png = match render_html_png(&target, width, height, 1.0, scope, backend).await {Ok(b) => b,Err(e) => return (format!("ERROR: {e}"), None),};@@ -4211,6 +4221,41 @@ mod tests {let _ = std::fs::remove_dir_all(&outside);}+ /// A page in a trusted root may load the files beside it; one the user+ /// approved outside every root may load only itself.+ #[cfg(feature = "tauri")]+ #[tokio::test]+ async fn screenshot_confines_a_page_outside_the_roots_to_itself() {+ let root = unique_root();+ let outside = unique_root();+ std::fs::write(root.join("in.html"), b"<h1>in</h1>").unwrap();+ let out_page = outside.join("out.html");+ std::fs::write(&out_page, b"<h1>out</h1>").unwrap();+ let out_page = out_page.to_str().unwrap();+ let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let seen_by_backend = seen.clone();+ let backend: ScreenshotBackend = std::sync::Arc::new(move |_, _, _, _, scope| {+ seen_by_backend.lock().unwrap().push(scope);+ Box::pin(async { Ok(b"png".to_vec()) })+ });++ for (path, read_roots) in [+ ("in.html", vec![]),+ (out_page, vec![]),+ (out_page, vec![outside.clone()]),+ ] {+ let (out, _) =+ screenshot(&json!({"path": path}), &root, None, &read_roots, Some(&backend)).await;+ assert!(!out.starts_with("ERROR"), "{out}");+ }+ assert_eq!(+ *seen.lock().unwrap(),+ [PageScope::Directory, PageScope::FileOnly, PageScope::Directory]+ );+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&outside);+ }+/// Renders for real when a browser is present, and returns an image part/// rather than a data URL buried in the text.#[cfg(feature = "tauri")]diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rsindex d8a433d3d..330f6c67e 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs@@ -344,7 +344,8 @@ pub fn shell_park_budget_secs(timeout_secs: u64) -> u64 {.clamp(MIN_PARK_SECS, MAX_PARK_SECS)}-/// Renders a local HTML/SVG file (path, width, height, scale) to PNG bytes.+/// Renders a local HTML/SVG file (path, width, height, scale, and what else the+/// page may load) to PNG bytes.////// Injected by the desktop so `screenshot` can capture through the app's own/// webview instead of shelling out to Chrome. A boxed closure so this module@@ -356,6 +357,7 @@ pub type ScreenshotBackend = std::sync::Arc<u64,u64,f64,+ crate::screenshot_pages::PageScope,) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<u8>, String>> + Send>,> + Senddiff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/webview_shot.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/webview_shot.rsindex f749c8be9..6ba5bfc48 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/webview_shot.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/webview_shot.rs@@ -21,6 +21,7 @@ use tauri::webview::PageLoadEvent;use tauri::{Runtime, WebviewUrl, WebviewWindowBuilder};use tokio::sync::oneshot;+use crate::screenshot_pages::PageScope;use crate::tools::ScreenshotBackend;const LOAD_TIMEOUT: Duration = Duration::from_secs(30);@@ -43,9 +44,9 @@ fn deliver(slot: &SnapshotSlot, value: Result<Vec<u8>, String>) {/// Build a [`ScreenshotBackend`] that captures through the app's webview.pub fn make_backend<R: Runtime>(app: &tauri::AppHandle<R>) -> ScreenshotBackend {let app = app.clone();- Arc::new(move |target, width, height, scale| {+ Arc::new(move |target, width, height, scale, scope| {let app = app.clone();- Box::pin(capture(app, target, width, height, scale))+ Box::pin(capture(app, target, width, height, scale, scope))})}@@ -58,6 +59,7 @@ async fn capture<R: Runtime>(// viewport DPR knob to honor here, so `scale` is accepted for signature// parity and left unapplied. The tool only ever passes 1.0._scale: f64,+ scope: PageScope,) -> Result<Vec<u8>, String> {let url = tauri::Url::from_file_path(&target).map_err(|_| format!("cannot build file URL for {}", target.display()))?;@@ -73,7 +75,7 @@ async fn capture<R: Runtime>(// Before the window exists, so its first navigation already finds it.// Dropped after `destroy()`, and on every early return.- crate::screenshot_pages::SCREENSHOT_PAGES.register(&label, &target)?;+ crate::screenshot_pages::SCREENSHOT_PAGES.register(&label, &target, scope)?;let _registered = Registered(label.clone());let (load_tx, load_rx) = oneshot::channel::<()>();@@ -528,7 +530,7 @@ mod tests {assert!(!frame_allowed(label, page_url.as_str()));crate::screenshot_pages::SCREENSHOT_PAGES- .register(label, &page)+ .register(label, &page, PageScope::Directory).unwrap();assert!(frame_allowed(label, page_url.as_str()));assert!(!frame_allowed(label, other_url.as_str()));diff --git a/src-tauri/src/core/navigation.rs b/src-tauri/src/core/navigation.rsindex 5f4976dc4..a03ce1b04 100644--- a/src-tauri/src/core/navigation.rs+++ b/src-tauri/src/core/navigation.rs@@ -179,6 +179,7 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {#[cfg(test)]mod tests {use super::*;+ use tauri_plugin_agent_tools::screenshot_pages::PageScope;fn u(s: &str) -> Url {Url::parse(s).unwrap()@@ -327,7 +328,9 @@ mod tests {let target = file_url(&dir.join("chart.html"));// Nothing recorded for the window yet.assert!(!allows_navigation_with(&shot, &target, None, &pages));- pages.register(&shot, &dir.join("chart.html")).unwrap();+ pages+ .register(&shot, &dir.join("chart.html"), PageScope::Directory)+ .unwrap();assert!(allows_navigation_with(&shot, &target, None, &pages));let sibling = file_url(&dir.join("assets/style.css"));assert!(allows_navigation_with(&shot, &sibling, None, &pages));@@ -352,7 +355,9 @@ mod tests {std::fs::write(secret.join("id_rsa"), "key").unwrap();let pages = ScreenshotPages::new();let shot = shot_label();- pages.register(&shot, &dir.join("chart.html")).unwrap();+ pages+ .register(&shot, &dir.join("chart.html"), PageScope::Directory)+ .unwrap();assert!(!allows_navigation_with(&shot,&file_url(&secret.join("id_rsa")),