Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(agent-tools): resolve dangling symlinks and stop link swaps in write/edit (#9424)
Akarshan Biswas840c33e65182
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.tomlindex 7fdd17542..1814d632f 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml+++ b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml@@ -68,7 +68,7 @@ tauri-plugin-websearch = { path = "../tauri-plugin-websearch", default-featurestauri-plugin = { version = "2.3.1", features = ["build"], optional = true }[target.'cfg(unix)'.dependencies]-nix = { version = "=0.30.1", features = ["signal", "process"] }+nix = { version = "=0.30.1", features = ["signal", "process", "fs"] }# Webview `screenshot` backend (see `webview_shot.rs`). All optional and enabled# by the `tauri` feature, so the headless CLI never pulls a GUI stack in.diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rsindex 7ad869e23..a726f9055 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs@@ -955,6 +955,37 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// A dangling link out of the project is an escape even under a session+ /// write grant: the prompt would name only the in-project link, so the user+ /// could not tell the write lands on, say, `~/.ssh/authorized_keys`.+ #[cfg(unix)]+ #[test]+ fn write_through_dangling_symlink_prompts_write_escape() {+ let root = unique_root();+ let outside = unique_root();+ std::os::unix::fs::symlink(outside.join("authorized_keys"), root.join("notes.md"))+ .unwrap();+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]);+ let mut grants = SessionGrants::default();+ grants.grant(PromptKind::Write);+ let d = resolve_decision(+ lookup("write").unwrap(),+ &json!({"path": "notes.md"}),+ &GateContext {+ project_root: &root,+ scratch: None,+ read_roots: &[],+ write_roots: &[],+ hidden_root: None,+ },+ &perms,+ &grants,+ );+ assert_eq!(d, Decision::Prompt(PromptKind::WriteEscape));+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&outside);+ }+#[test]fn session_grant_allows_write_escape() {let root = unique_root();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 6f2b1e681..828887804 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@@ -13,9 +13,10 @@ use crate::memory;use crate::skills;use crate::tools::jail;use crate::tools::proc;+use crate::tools::nofollow;use crate::tools::sandbox::{- escapes_write_roots, hidden_under, in_scratch, lexical_normalize, refuse_windows_name,- resolve_path, scratch_display_path, symlink_escapes_any_root,+ 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::tools::{BuiltinTool, ImageContentPart, ScreenshotBackend, ToolContext};@@ -740,34 +741,56 @@ async fn write(// Report the resolved location, not the raw argument: an absolute or `../`// path lands outside the project and the model must see where it went.let shown = display_path(root, scratch, &target);- // Re-validate before `create_dir_all`, not just before the write: a- // concurrent sandboxed process can swap a path component between the gate- // decision and this call, and creating the parents first would already have- // made directories through the swapped link. Fail closed.- if symlink_escapes_any_root(root, scratch, write_roots, &target) {- return format!("ERROR: refused to write through a symlink out of the workspace: {path}");- }- if let Some(parent) = target.parent() {- if let Err(e) = tokio::fs::create_dir_all(parent).await {- return format!("ERROR: {shown}: {e}");+ // Resolve once, before any directory is created, and open only what that+ // resolution approved: a concurrent sandboxed process can swap a path+ // component for a link at any point, and both `create_dir_all` and a+ // by-name write would follow it.+ let real = match write_landing(root, scratch, write_roots, &target) {+ Ok(real) => real,+ Err(()) => {+ return format!("ERROR: refused to write through a symlink out of the workspace: {path}")}- }- // Existence decides created/overwrote; a non-UTF8 file still exists, so it- // must not be read_to_string's error path that answers that question.- let existed = tokio::fs::try_exists(&target).await.unwrap_or(false);- let unchanged = existed- && tokio::fs::read_to_string(&target)- .await- .is_ok_and(|prior| prior == content);- let bytes = content.len();- match tokio::fs::write(&target, content).await {- Ok(()) if unchanged => format!("No change: {shown} already had these {bytes} bytes"),- Ok(()) if existed => format!("Overwrote {shown} ({bytes} bytes)"),- Ok(()) => format!("Created {shown} ({bytes} bytes)"),+ };+ let content = content.to_string();+ let outcome = tokio::task::spawn_blocking(move || {+ // Existence decides created/overwrote; a non-UTF8 file still exists, so+ // it must not be a failed UTF-8 decode that answers that question.+ let prior = nofollow::read(&real);+ let existed = !matches!(&prior, Err(e) if e.kind() == std::io::ErrorKind::NotFound);+ let unchanged = prior.is_ok_and(|p| p == content.as_bytes());+ nofollow::write(&real, content.as_bytes()).map(|()| (existed, unchanged, content.len()))+ })+ .await;+ match outcome {+ Ok(Ok((_, true, bytes))) => format!("No change: {shown} already had these {bytes} bytes"),+ Ok(Ok((true, _, bytes))) => format!("Overwrote {shown} ({bytes} bytes)"),+ Ok(Ok((false, _, bytes))) => format!("Created {shown} ({bytes} bytes)"),+ Ok(Err(e)) if nofollow::is_link_refused(&e) => {+ format!("ERROR: refused to write through a symlink out of the workspace: {path}")+ }+ Ok(Err(e)) => format!("ERROR: {shown}: {e}"),Err(e) => format!("ERROR: {shown}: {e}"),}}+/// The link-free path a `write`/`edit` must open, or `Err` to refuse.+///+/// A target under a trusted root must resolve inside one. A target outside+/// every root was already put to the user by the gate as an escape, so it is+/// written where it really lands; one that cannot be resolved at all is+/// refused rather than handed to a by-name open.+fn write_landing(+ root: &Path,+ scratch: Option<&Path>,+ write_roots: &[PathBuf],+ target: &Path,+) -> Result<PathBuf, ()> {+ match landing(root, scratch, write_roots, target) {+ Landing::Inside(real) | Landing::Outside(Some(real)) => Ok(real),+ Landing::Escapes | Landing::Outside(None) => Err(()),+ }+}+/// Make an edit's line endings agree with the file it targets.////// `read` hands the model a CRLF file verbatim, but a model writes a plain `\n`@@ -819,13 +842,22 @@ async fn edit(return format!("ERROR: refused to edit outside the agent workspace: {path}");}let shown = display_path(root, scratch, &target);- // Re-validate before the final read+write pair so a swapped symlink cannot- // redirect either the read or the later write.- if symlink_escapes_any_root(root, scratch, write_roots, &target) {+ // Resolve once and use that path for both the read and the write, each+ // opened without following links, so a swapped component redirects neither.+ let Ok(real) = write_landing(root, scratch, write_roots, &target) else {return format!("ERROR: refused to edit through a symlink out of the workspace: {path}");- }- let mut content = match tokio::fs::read_to_string(&target).await {- Ok(c) => c,+ };+ let read_path = real.clone();+ let read = tokio::task::spawn_blocking(move || nofollow::read(&read_path)).await;+ let mut content = match read {+ Ok(Ok(bytes)) => match String::from_utf8(bytes) {+ Ok(c) => c,+ Err(_) => return format!("ERROR: {shown}: stream did not contain valid UTF-8"),+ },+ Ok(Err(e)) if nofollow::is_link_refused(&e) => {+ return format!("ERROR: refused to edit through a symlink out of the workspace: {path}")+ }+ Ok(Err(e)) => return format!("ERROR: {shown}: {e}"),Err(e) => return format!("ERROR: {shown}: {e}"),};@@ -850,8 +882,13 @@ async fn edit(content = content.replacen(&*old_string, &new_string, 1);}- match tokio::fs::write(&target, content).await {- Ok(()) => format!("Applied {} edit(s) to {shown}", edits.len()),+ let written = tokio::task::spawn_blocking(move || nofollow::write(&real, content.as_bytes()));+ match written.await {+ Ok(Ok(())) => format!("Applied {} edit(s) to {shown}", edits.len()),+ Ok(Err(e)) if nofollow::is_link_refused(&e) => {+ format!("ERROR: refused to edit through a symlink out of the workspace: {path}")+ }+ Ok(Err(e)) => format!("ERROR: {shown}: {e}"),Err(e) => format!("ERROR: {shown}: {e}"),}}@@ -2596,6 +2633,59 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// A write through a dangling link out of the project must not create the+ /// link's target, confined or not: the handler's symlink re-check is what+ /// stands between an approved in-project name and the host file.+ #[cfg(unix)]+ #[tokio::test]+ async fn write_through_dangling_symlink_is_refused() {+ let root = unique_root();+ let outside = unique_root();+ let target = outside.join("authorized_keys");+ std::os::unix::fs::symlink(&target, root.join("notes.md")).unwrap();+ let store = crate::workspace::project_store(&root);+ for confine in [false, true] {+ let ctx = ToolContext::new(&root, &store, &[]).with_confined_writes(confine);+ let out = super::execute_builtin(+ lookup("write").unwrap(),+ &json!({"path": "notes.md", "content": "ATTACKER"}),+ &ctx,+ )+ .await+ .0;+ assert!(out.starts_with("ERROR: refused to write"), "confine={confine}: {out}");+ assert!(!target.exists(), "confine={confine}: target was created");+ }+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&outside);+ }++ /// Links that stay inside the project (a yarn workspace's shape) keep+ /// working for both `write` and `edit`, landing on the real file.+ #[cfg(unix)]+ #[tokio::test]+ async fn write_and_edit_follow_an_in_project_link() {+ let root = unique_root();+ std::fs::create_dir_all(root.join("pkg")).unwrap();+ std::os::unix::fs::symlink(root.join("pkg"), root.join("linked")).unwrap();+ let w = execute_builtin(+ lookup("write").unwrap(),+ &json!({"path": "linked/new/a.txt", "content": "one"}),+ &root,+ )+ .await;+ assert_eq!(w, "Created linked/new/a.txt (3 bytes)");+ let e = execute_builtin(+ lookup("edit").unwrap(),+ &json!({"path": "linked/new/a.txt", "edits": [{"old_string": "one", "new_string": "two"}]}),+ &root,+ )+ .await;+ assert_eq!(e, "Applied 1 edit(s) to linked/new/a.txt");+ assert_eq!(std::fs::read_to_string(root.join("pkg/new/a.txt")).unwrap(), "two");+ let _ = std::fs::remove_dir_all(&root);+ }+/// With write confinement enabled, a `..` write is refused at the handler,/// independent of the gate -- the defense-in-depth layer.#[tokio::test]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 77d3fabf9..d8a433d3d 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@@ -20,6 +20,9 @@ pub mod jail;/// The `monitor` tool's core: file watching + condition-script evaluation./// Loop-dispatched (like the subagent tools), so it is not in `BUILTIN_TOOLS`.pub mod monitor;+/// Opens a resolved path refusing every link on the way, so a write lands on+/// exactly the path the containment check approved.+pub mod nofollow;/// Tools an installed plugin declares in its `plugin.toml`. Loop-dispatched/// like the monitor tool, so they are not in `BUILTIN_TOOLS`.pub mod plugin_tools;diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/nofollow.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/nofollow.rsnew file mode 100644index 000000000..87226e214--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/nofollow.rs@@ -0,0 +1,386 @@+//! Open a fully resolved path without following any link along it.+//!+//! The filesystem tools decide where a path lands ([`super::sandbox::landing`])+//! and only then touch it. Reopening the path by name afterwards would resolve+//! it a second time, and a link swapped into it in between (the sandboxed shell+//! can write the project) would carry the write somewhere the check never saw.+//! These helpers take the already-resolved path, which contains no links, and+//! walk it one directory at a time refusing any link they meet, so the file+//! they open is the one that was checked or nothing at all.+//!+//! Unix walks with `openat(O_NOFOLLOW)` relative to the previous directory's+//! descriptor. Windows has no `openat` in std, so each ancestor is held open+//! without `FILE_SHARE_DELETE`, which keeps it from being renamed or replaced+//! while the walk below it runs, and each node is probed with+//! `FILE_FLAG_OPEN_REPARSE_POINT` and refused if it is a link or junction. The+//! leaf is then reopened normally, so cloud placeholders still download.++use std::io::{self, Read, Write};+use std::path::Path;++/// Marker for "a link was found where the resolved path had none": the path was+/// changed between the containment check and the open.+#[derive(Debug)]+pub struct LinkRefused;++impl std::fmt::Display for LinkRefused {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str("a path component became a symbolic link")+ }+}++impl std::error::Error for LinkRefused {}++/// True iff `e` is the [`LinkRefused`] refusal rather than an ordinary I/O error.+pub fn is_link_refused(e: &io::Error) -> bool {+ e.get_ref().is_some_and(|inner| inner.is::<LinkRefused>())+}++fn refused() -> io::Error {+ io::Error::other(LinkRefused)+}++fn invalid(path: &Path) -> io::Error {+ io::Error::new(+ io::ErrorKind::InvalidInput,+ format!("not an absolute resolved path: {}", path.display()),+ )+}++/// Read the file at the resolved `path`.+pub fn read(path: &Path) -> io::Result<Vec<u8>> {+ let mut file = imp::open_leaf(path, false)?;+ let mut buf = Vec::new();+ file.read_to_end(&mut buf)?;+ Ok(buf)+}++/// Create or truncate the file at the resolved `path` and write `bytes`,+/// creating any missing parent directories on the way.+pub fn write(path: &Path, bytes: &[u8]) -> io::Result<()> {+ let mut file = imp::open_leaf(path, true)?;+ file.write_all(bytes)?;+ file.flush()+}++#[cfg(unix)]+mod imp {+ use super::{invalid, refused};+ use nix::errno::Errno;+ use nix::fcntl::{openat, AtFlags, OFlag, AT_FDCWD};+ use nix::sys::stat::{fstatat, mkdirat, Mode, SFlag};+ use std::ffi::OsStr;+ use std::fs::File;+ use std::io;+ use std::os::fd::OwnedFd;+ use std::path::{Component, Path};++ /// A directory descriptor that needs only search permission on the+ /// directory, so a `711` parent (common for `/home/<user>`) still walks.+ #[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))]+ const DIR: OFlag = OFlag::O_PATH;+ #[cfg(any(target_os = "macos", target_os = "ios"))]+ const DIR: OFlag = OFlag::O_SEARCH;+ #[cfg(not(any(+ target_os = "linux",+ target_os = "android",+ target_os = "freebsd",+ target_os = "macos",+ target_os = "ios"+ )))]+ const DIR: OFlag = OFlag::O_RDONLY;++ /// Map a failed no-follow open of `name` under `dir`: a link there is the+ /// swap this module exists to catch. Platforms disagree on the errno+ /// (`ELOOP`, or `ENOTDIR` when `O_DIRECTORY` sees the link), so ask the+ /// directory what the entry is instead of trusting the code.+ fn classify(dir: &OwnedFd, name: &OsStr, err: Errno) -> io::Error {+ match fstatat(dir, name, AtFlags::AT_SYMLINK_NOFOLLOW) {+ Ok(st) if SFlag::from_bits_truncate(st.st_mode) & SFlag::S_IFMT == SFlag::S_IFLNK => {+ refused()+ }+ _ => err.into(),+ }+ }++ pub(super) fn open_leaf(path: &Path, create: bool) -> io::Result<File> {+ let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else {+ return Err(invalid(path));+ };+ let mut comps = parent.components();+ if comps.next() != Some(Component::RootDir) {+ return Err(invalid(path));+ }+ let dir_flags = DIR | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;+ let mut dir = openat(AT_FDCWD, "/", dir_flags, Mode::empty())?;+ for c in comps {+ let Component::Normal(part) = c else {+ return Err(invalid(path));+ };+ if create {+ match mkdirat(&dir, part, Mode::from_bits_truncate(0o777)) {+ Ok(()) | Err(Errno::EEXIST) => {}+ Err(e) => return Err(e.into()),+ }+ }+ dir = match openat(&dir, part, dir_flags, Mode::empty()) {+ Ok(next) => next,+ Err(e) => return Err(classify(&dir, part, e)),+ };+ }+ let flags = if create {+ OFlag::O_WRONLY | OFlag::O_CREAT | OFlag::O_TRUNC+ } else {+ OFlag::O_RDONLY+ } | OFlag::O_NOFOLLOW+ | OFlag::O_CLOEXEC;+ match openat(&dir, name, flags, Mode::from_bits_truncate(0o666)) {+ Ok(fd) => Ok(File::from(fd)),+ Err(e) => Err(classify(&dir, name, e)),+ }+ }+}++#[cfg(windows)]+mod imp {+ use super::{invalid, refused};+ use std::fs::{File, OpenOptions};+ use std::io;+ use std::os::windows::fs::OpenOptionsExt;+ use std::path::{Component, Path, PathBuf};+ use windows_sys::Win32::Storage::FileSystem::{+ FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES,+ FILE_SHARE_READ, FILE_SHARE_WRITE,+ };++ /// No `FILE_SHARE_DELETE`: while this handle lives, nobody can rename,+ /// delete or replace the node, which is what pins the walked chain.+ const SHARE: u32 = FILE_SHARE_READ | FILE_SHARE_WRITE;++ /// Refuse a link or junction. `File::metadata` reads the reparse tag, so+ /// `is_symlink` is true only for name-surrogate tags: a OneDrive+ /// placeholder is also a reparse point and must stay writable.+ fn reject_link(file: &File) -> io::Result<std::fs::Metadata> {+ let meta = file.metadata()?;+ if meta.file_type().is_symlink() {+ return Err(refused());+ }+ Ok(meta)+ }++ fn pin_dir(path: &Path) -> io::Result<File> {+ let dir = OpenOptions::new()+ .access_mode(FILE_READ_ATTRIBUTES)+ .share_mode(SHARE)+ .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)+ .open(path)?;+ if !reject_link(&dir)?.is_dir() {+ return Err(io::Error::new(+ io::ErrorKind::NotADirectory,+ format!("not a directory: {}", path.display()),+ ));+ }+ Ok(dir)+ }++ /// Open the leaf itself, never what a link there points at, holding it+ /// against rename and delete. With `create`, a missing leaf is created as+ /// a plain file: `create_new` refuses to reuse anything already there,+ /// a dangling link included, so the retry re-probes what appeared.+ fn probe_leaf(path: &Path, create: bool) -> io::Result<File> {+ let probe = || {+ OpenOptions::new()+ .access_mode(FILE_READ_ATTRIBUTES)+ .share_mode(SHARE)+ .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)+ .open(path)+ };+ match probe() {+ Err(e) if create && e.kind() == io::ErrorKind::NotFound => {}+ other => return other,+ }+ match OpenOptions::new()+ .write(true)+ .create_new(true)+ .share_mode(SHARE)+ .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)+ .open(path)+ {+ Err(e) if e.kind() == io::ErrorKind::AlreadyExists => probe(),+ other => other,+ }+ }++ pub(super) fn open_leaf(path: &Path, create: bool) -> io::Result<File> {+ let (Some(parent), Some(_)) = (path.parent(), path.file_name()) else {+ return Err(invalid(path));+ };+ if !parent.has_root() {+ return Err(invalid(path));+ }+ let mut walked = PathBuf::new();+ let mut held: Vec<File> = Vec::new();+ for c in parent.components() {+ match c {+ Component::Prefix(_) => {+ walked.push(c.as_os_str());+ continue;+ }+ Component::RootDir => walked.push(c.as_os_str()),+ Component::Normal(part) => {+ walked.push(part);+ if create {+ match std::fs::create_dir(&walked) {+ Ok(()) => {}+ Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}+ Err(e) => return Err(e),+ }+ }+ }+ _ => return Err(invalid(path)),+ }+ held.push(pin_dir(&walked)?);+ }+ // The leaf is checked through a probe and used through a second, plain+ // open. Opening it with OPEN_REPARSE_POINT for real would hand back a+ // cloud-only OneDrive placeholder undownloaded, so reads would see the+ // stub. The probe holds the leaf without FILE_SHARE_DELETE, so it is+ // still the same file when the plain open follows.+ let probe = probe_leaf(path, create)?;+ reject_link(&probe)?;+ let mut opts = OpenOptions::new();+ opts.share_mode(SHARE);+ if create {+ // Not `truncate`: kept symmetric with the probe; emptied below.+ opts.write(true);+ } else {+ opts.read(true);+ }+ let file = opts.open(path)?;+ drop(probe);+ if create {+ file.set_len(0)?;+ }+ drop(held);+ Ok(file)+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::path::PathBuf;+ use std::sync::atomic::{AtomicUsize, Ordering};++ static COUNTER: AtomicUsize = AtomicUsize::new(0);++ /// A directory link. Windows uses a junction: it needs no privilege, so the+ /// test runs on every Windows machine, and it is the link a sandboxed+ /// process could actually plant.+ fn link_dir(target: &Path, link: &Path) {+ #[cfg(unix)]+ std::os::unix::fs::symlink(target, link).unwrap();+ #[cfg(windows)]+ {+ let status = std::process::Command::new("cmd")+ .arg("/C")+ .arg("mklink")+ .arg("/J")+ .arg(link)+ .arg(target)+ .stdout(std::process::Stdio::null())+ .status()+ .unwrap();+ assert!(status.success(), "mklink /J failed");+ }+ }++ /// A file link, or `false` where the platform will not make one: Windows+ /// file symlinks need Developer Mode or elevation. CI runners have it, so+ /// there a refusal is a failure, not a skip.+ fn link_file(target: &Path, link: &Path) -> bool {+ #[cfg(unix)]+ let made = std::os::unix::fs::symlink(target, link);+ #[cfg(windows)]+ let made = std::os::windows::fs::symlink_file(target, link);+ match made {+ Ok(()) => true,+ Err(e) if std::env::var_os("CI").is_none() => {+ eprintln!("skipping: cannot create a file symlink here: {e}");+ false+ }+ Err(e) => panic!("file symlink on CI: {e}"),+ }+ }++ fn dir() -> PathBuf {+ let n = COUNTER.fetch_add(1, Ordering::SeqCst);+ let d = std::env::temp_dir()+ .join(format!("jan_nofollow_test_{}_{}", std::process::id(), n));+ std::fs::create_dir_all(&d).unwrap();+ // Unix: macOS's temp dir sits behind the `/var -> /private/var` link,+ // which the walk would rightly refuse. Windows: keep the plain+ // spelling, since `mklink` does not take a `\\?\` path.+ #[cfg(unix)]+ let d = d.canonicalize().unwrap();+ d+ }++ #[test]+ fn writes_and_reads_creating_parents() {+ let root = dir();+ let target = root.join("a").join("b").join("c.txt");+ write(&target, b"hello").unwrap();+ assert_eq!(read(&target).unwrap(), b"hello");+ write(&target, b"hi").unwrap();+ assert_eq!(std::fs::read(&target).unwrap(), b"hi", "truncates");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A link swapped in for a directory after the path was resolved: the walk+ /// must stop there instead of writing on the far side.+ #[test]+ fn a_link_in_a_directory_component_is_refused() {+ let root = dir();+ let outside = dir();+ link_dir(&outside, &root.join("sub"));+ let through = root.join("sub").join("x.txt");+ for create in [true, false] {+ let err = if create {+ write(&through, b"x").unwrap_err()+ } else {+ read(&through).unwrap_err()+ };+ assert!(is_link_refused(&err), "create={create}: {err}");+ }+ assert!(!outside.join("x.txt").exists());+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&outside);+ }++ /// The leaf itself swapped for a link, dangling or not: neither is followed.+ #[test]+ fn a_link_at_the_leaf_is_refused() {+ let root = dir();+ let outside = dir();+ std::fs::write(outside.join("existing"), b"keep").unwrap();+ if !link_file(&outside.join("existing"), &root.join("a"))+ || !link_file(&outside.join("new"), &root.join("b"))+ {+ return;+ }+ assert!(is_link_refused(&write(&root.join("a"), b"x").unwrap_err()));+ assert!(is_link_refused(&write(&root.join("b"), b"x").unwrap_err()));+ assert!(is_link_refused(&read(&root.join("a")).unwrap_err()));+ assert_eq!(std::fs::read(outside.join("existing")).unwrap(), b"keep");+ assert!(!outside.join("new").exists());+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&outside);+ }++ #[test]+ fn a_relative_path_is_rejected() {+ let err = write(Path::new("rel/x.txt"), b"x").unwrap_err();+ assert_eq!(err.kind(), io::ErrorKind::InvalidInput);+ }+}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rsindex c2fe4d026..2756f13df 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs@@ -381,8 +381,8 @@ pub fn hidden_under(base: &Path, hidden: &Path) -> Option<PathBuf> {/// override their approval. An unresolvable path fails closed.////// Still a re-check, not a guarantee: a swap landing between this call and the-/// open is not covered. That needs descriptor-relative no-follow opens-/// (`openat2` with `RESOLVE_BENEATH`, reparse-point handling on Windows).+/// open is not covered. A handler that writes resolves once with [`landing`]+/// and opens the result through [`super::nofollow`], which closes that window.pub fn symlink_escapes_root(project_root: &Path, scratch: Option<&Path>, target: &Path) -> bool {symlink_escapes_any_root(project_root, scratch, &[], target)}@@ -399,65 +399,128 @@ pub fn symlink_escapes_any_root(read_roots: &[PathBuf],target: &Path,) -> bool {- let mut roots = vec![project_root];+ matches!(landing(project_root, scratch, read_roots, target), Landing::Escapes)+}++/// Where a handler's target really lands, see [`landing`].+#[derive(Debug, PartialEq, Eq)]+pub enum Landing {+ /// Under a trusted root, and resolves (every link followed) inside one.+ Inside(PathBuf),+ /// Claims a trusted root but resolves outside all of them, or cannot be+ /// resolved at all: refuse.+ Escapes,+ /// Not lexically under any root: an escape the gate already put to the+ /// user. Carries the real path when it resolves.+ Outside(Option<PathBuf>),+}++/// Resolve `target` once and classify it against the trusted roots.+///+/// A writer must open exactly the path this returns rather than re-resolving+/// `target`: two resolutions leave room for a link swapped in between to send+/// the second one somewhere the first was never checked against.+pub fn landing(+ project_root: &Path,+ scratch: Option<&Path>,+ roots: &[PathBuf],+ target: &Path,+) -> Landing {+ let mut all = vec![project_root];if let Some(s) = scratch {- roots.push(s);+ all.push(s);}- for r in read_roots {- roots.push(r.as_path());+ for r in roots {+ all.push(r.as_path());}let normalized = lexical_normalize(target);- if !roots+ if !all.iter().any(|r| normalized.starts_with(lexical_normalize(r))){- return false;+ return Landing::Outside(canonicalize_lenient(&normalized).ok());}let Ok(resolved) = canonicalize_lenient(&normalized) else {- return true;+ return Landing::Escapes;};- !roots+ if all.iter().filter_map(|r| r.canonicalize().ok()).any(|r| resolved.starts_with(r))+ {+ Landing::Inside(resolved)+ } else {+ Landing::Escapes+ }}-/// Canonicalize a path that may not fully exist: canonicalize the deepest-/// existing ancestor, then re-append the non-existing tail (resolving `.`/`..`-/// lexically). Errors only if no ancestor up to root exists.+/// Canonicalize a path that may not fully exist, resolving `.`/`..` lexically+/// past the point where the path stops existing.+///+/// Walked one component at a time so every symlink on the way is followed,+/// including a dangling one: `canonicalize` fails on a link whose target does+/// not exist, yet a write through it creates that target. Re-appending such a+/// link by name would keep `notes.md -> ~/.ssh/authorized_keys` inside the+/// project. A link's target is spliced in place of its name instead, relative+/// targets against the link's own directory, as the kernel does. Too many hops+/// (a cycle) is an error, so callers fail closed.fn canonicalize_lenient(path: &Path) -> Result<PathBuf, String> {+ use std::path::Component;+ // Linux's MAXSYMLINKS: the most hops `open` itself would follow.+ const MAX_HOPS: usize = 40;if let Ok(p) = path.canonicalize() {return Ok(p);}- let mut existing = path;- let mut tail: Vec<&std::ffi::OsStr> = Vec::new();- loop {- match existing.parent() {- Some(parent) => {- if let Some(name) = existing.file_name() {- tail.push(name);- }- existing = parent;- if let Ok(base) = existing.canonicalize() {- let mut result = base;- for comp in tail.iter().rev() {- if *comp == std::ffi::OsStr::new(".") {- continue;- }- if *comp == std::ffi::OsStr::new("..") {- result.pop();- } else {- result.push(comp);- }- }- return Ok(result);+ let abs = if path.is_absolute() {+ path.to_path_buf()+ } else {+ std::env::current_dir()+ .map_err(|e| format!("current dir: {e}"))?+ .join(path)+ };+ // Components still to resolve, next one last so a link splices onto the end.+ let mut pending: Vec<std::ffi::OsString> =+ abs.components().rev().map(|c| c.as_os_str().to_owned()).collect();+ let mut resolved = PathBuf::new();+ let mut hops = 0;+ while let Some(raw) = pending.pop() {+ match Path::new(&raw).components().next() {+ Some(Component::Prefix(_) | Component::RootDir) => {+ resolved.push(&raw);+ if let Ok(root) = resolved.canonicalize() {+ resolved = root;}}- None => {- return Err(format!("no existing ancestor for {:?}", path));+ Some(Component::ParentDir) => {+ resolved.pop();}+ Some(Component::Normal(name)) => {+ let candidate = resolved.join(name);+ if let Ok(real) = candidate.canonicalize() {+ resolved = real;+ continue;+ }+ let is_link = std::fs::symlink_metadata(&candidate)+ .is_ok_and(|m| m.file_type().is_symlink());+ if !is_link {+ // Does not exist: nothing below it can be a link either way.+ resolved = candidate;+ continue;+ }+ hops += 1;+ if hops > MAX_HOPS {+ return Err(format!("too many levels of symbolic links in {:?}", path));+ }+ let target = std::fs::read_link(&candidate)+ .map_err(|e| format!("read link {:?}: {e}", candidate))?;+ // An absolute target restarts from its own root when its+ // RootDir component is popped; a relative one stays here.+ pending.extend(target.components().rev().map(|c| c.as_os_str().to_owned()));+ }+ Some(Component::CurDir) | None => {}}}+ Ok(resolved)}#[cfg(test)]@@ -710,6 +773,59 @@ mod tests {let _ = std::fs::remove_dir_all(&outside);}+ /// A dangling link (its target does not exist yet) is still a link: a write+ /// through it creates the target. Resolving only the deepest existing+ /// ancestor and re-appending the rest lexically kept the in-project name,+ /// so `notes.md -> ~/.ssh/authorized_keys` passed as an in-project write.+ #[cfg(unix)]+ #[test]+ fn dangling_symlink_out_of_the_project_escapes() {+ let root = unique_root();+ let outside = unique_root();+ std::os::unix::fs::symlink(outside.join("authorized_keys"), root.join("notes.md"))+ .unwrap();+ // A dangling directory link: the tail hangs off a link that resolves nowhere.+ std::os::unix::fs::symlink(outside.join("no-such-dir"), root.join("d")).unwrap();+ // Relative targets resolve against the link's own directory.+ std::fs::create_dir_all(root.join("sub")).unwrap();+ let rel = Path::new("../..").join(outside.file_name().unwrap()).join("rel.txt");+ std::os::unix::fs::symlink(&rel, root.join("sub/rel.md")).unwrap();++ assert_eq!(escapes_project(&root, None, "notes.md"), Ok(true));+ assert_eq!(escapes_project(&root, None, "d/x.txt"), Ok(true));+ assert_eq!(escapes_project(&root, None, "sub/rel.md"), Ok(true));+ assert_eq!(escapes_project(&root, None, "missing/../notes.md"), Ok(true));+ assert_eq!(escapes_write_roots(&root, None, &[], "notes.md"), Ok(true));+ assert!(symlink_escapes_root(&root, None, &root.join("notes.md")));+ assert!(symlink_escapes_root(&root, None, &root.join("d/x.txt")));+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&outside);+ }++ /// A dangling link that stays inside the project is an ordinary write.+ #[cfg(unix)]+ #[test]+ fn dangling_symlink_inside_the_project_does_not_escape() {+ let root = unique_root();+ std::fs::create_dir_all(root.join("docs")).unwrap();+ std::os::unix::fs::symlink("docs/README.md", root.join("README.md")).unwrap();+ assert_eq!(escapes_project(&root, None, "README.md"), Ok(false));+ assert!(!symlink_escapes_root(&root, None, &root.join("README.md")));+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A link cycle resolves to nothing: fail closed rather than loop.+ #[cfg(unix)]+ #[test]+ fn symlink_cycle_fails_closed() {+ let root = unique_root();+ std::os::unix::fs::symlink("b", root.join("a")).unwrap();+ std::os::unix::fs::symlink("a", root.join("b")).unwrap();+ assert!(escapes_project(&root, None, "a").is_err());+ assert!(symlink_escapes_root(&root, None, &root.join("a")));+ let _ = std::fs::remove_dir_all(&root);+ }+/// The re-check flags only symlinks that *leave* the trusted roots. An/// in-root link (the shape every yarn workspace has) resolves back inside/// and must stay usable; a link out of the root is an escape; a path that