Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

tech(RUST): 13 Gegenpruefungs-Befunde + oauth-Nachtrag, jeder mit Mutationsprobe

Daviddab30435d005
diff --git a/src-tauri/src/commands/agent.rs b/src-tauri/src/commands/agent.rs
index 5e1e2905..668f74ab 100644
--- a/src-tauri/src/commands/agent.rs
+++ b/src-tauri/src/commands/agent.rs
@@ -419,38 +419,12 @@ pub async fn execute_code(
/// paths included) was readable by every account on the box, and a racing local
/// process could swap the file between the write and the spawn.
///
-/// `TempDir` creates a directory with a random name and removes it with its
-/// contents when the returned handle drops — including on every early return of
-/// the caller. The 0700 mode is passed to `mkdir` itself rather than chmod'ed
-/// afterwards (tempfile defaults to the umask, i.e. 0755), so the directory is
-/// never briefly readable. The file is created with `create_new`, so a
-/// pre-placed name is an error rather than a target, and 0600.
+/// The mechanics — 0700 directory, `create_new` 0600 file, lifetime owned by
+/// the returned handle — live in `private_tmp`, because the dictation take in
+/// commands/whisper.rs is the same problem and used to carry its own unfixed
+/// copy of this code.
fn write_private_script(code: &str) -> Result<(tempfile::TempDir, PathBuf), String> {
- use std::io::Write;
- let mut builder = tempfile::Builder::new();
- builder.prefix("lu-agent-code-");
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- builder.permissions(std::fs::Permissions::from_mode(0o700));
- }
- let dir = builder
- .tempdir()
- .map_err(|e| format!("Create temp dir: {}", os_error::english(&e)))?;
- let path = dir.path().join("agent-code.py");
- let mut opts = fs::OpenOptions::new();
- opts.write(true).create_new(true);
- #[cfg(unix)]
- {
- use std::os::unix::fs::OpenOptionsExt;
- opts.mode(0o600);
- }
- let mut file = opts
- .open(&path)
- .map_err(|e| format!("Write temp script: {}", os_error::english(&e)))?;
- file.write_all(code.as_bytes())
- .map_err(|e| format!("Write temp script: {}", os_error::english(&e)))?;
- Ok((dir, path))
+ crate::private_tmp::write_private_temp("lu-agent-code-", "agent-code.py", code.as_bytes())
}
#[allow(non_snake_case)]
@@ -640,12 +614,15 @@ pub(crate) fn set_chat_workspace_override_impl(
let pb = std::path::PathBuf::from(p);
// This path becomes a JAIL ROOT for every later file op of this
// chat, including the ones the remote bridge serves — so it is
- // checked here, once, instead of being trusted on every call. It is
- // then remembered as a user-picked root, which is what lets a
- // folder outside the structural rules (a mount point, a short path)
- // work once the user has actually chosen it in the dialog.
+ // checked here, once, instead of being trusted on every call.
+ //
+ // Checked, and deliberately NOT recorded as picked: `path` arrived
+ // over IPC from the WebView, so recording it here would let the
+ // caller write its own entry into the allowlist that constrains it.
+ // The folder becomes allowed in `system::pick_folder`, i.e. when a
+ // human chooses it in the native dialog — which is exactly what the
+ // frontend does immediately before calling this.
crate::commands::filesystem::validate_workspace_root(&pb)?;
- crate::commands::filesystem::remember_picked_root(&pb);
// Best-effort: create the folder if missing so the first
// file_write doesn't fail with "no such directory".
let _ = std::fs::create_dir_all(&pb);
@@ -856,14 +833,42 @@ mod workspace_override_tests {
);
}
- /// The real flow: the user picks a folder, it is stored, and it is
- /// remembered as picked so the fs tools accept it as a root.
+ /// The command takes its path from the WebView, so it may VALIDATE against
+ /// the allowlist but must never write to it. A folder nobody chose in the
+ /// native dialog is refused however ordinary it looks — otherwise a
+ /// compromised renderer would simply name its own jail root and the
+ /// allowlist would constrain nothing.
+ #[test]
+ fn a_folder_that_was_never_picked_cannot_be_made_a_workspace() {
+ let state = AppState::new();
+ let dir = std::env::temp_dir().join(format!("lu-unpicked-{}", std::process::id()));
+ let _ = fs::create_dir_all(&dir);
+ let s = dir.to_string_lossy().to_string();
+
+ let got = set_chat_workspace_override_impl("__remote__", Some(&s), &state);
+ assert!(got.is_err(), "an unpicked folder became a jail root: {got:?}");
+ assert!(
+ state.chat_workspace_overrides.lock().unwrap().is_empty(),
+ "a refused root was still stored",
+ );
+ assert!(
+ crate::commands::filesystem::validate_workspace_root(&dir).is_err(),
+ "the refused call still added the folder to the allowlist",
+ );
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ /// The real flow: the user picks a folder in the native dialog (which is
+ /// what puts it on the allowlist), the frontend passes that path here, and
+ /// it is stored.
#[test]
fn a_picked_project_folder_is_stored_and_trusted_afterwards() {
let state = AppState::new();
let dir = std::env::temp_dir().join(format!("lu-ovr-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
let s = dir.to_string_lossy().to_string();
+ // `system::pick_folder` does this for real; the dialog cannot run here.
+ crate::commands::filesystem::allow_root_for_test(&dir);
set_chat_workspace_override_impl("__remote__", Some(&s), &state).expect("accepted");
assert_eq!(
diff --git a/src-tauri/src/commands/bg_tasks.rs b/src-tauri/src/commands/bg_tasks.rs
index 3f846319..493fa7cc 100644
--- a/src-tauri/src/commands/bg_tasks.rs
+++ b/src-tauri/src/commands/bg_tasks.rs
@@ -35,6 +35,15 @@ const CREATE_NO_WINDOW: u32 = 0x08000000;
const TAIL_BYTES: usize = 64 * 1024;
+/// How often the reader task checks whether the child has exited.
+///
+/// It polls instead of awaiting `child.wait()` because the reap has to happen
+/// under the task lock, together with clearing the pid — see the loop in
+/// `shell_task_start_impl`. These tasks are builds and installs; 50 ms of
+/// latency on noticing the exit of a multi-minute command is not observable,
+/// and it buys an ordering the shutdown sweep can rely on.
+const REAP_POLL: std::time::Duration = std::time::Duration::from_millis(50);
+
#[derive(Clone, Debug, Serialize)]
pub struct BgTaskStatus {
pub id: String,
@@ -106,6 +115,22 @@ impl BgRegistry {
static REGISTRY: Lazy<BgRegistry> = Lazy::new(BgRegistry::default);
+/// Test isolation for the process-wide registry.
+///
+/// `kill_all_background_tasks` kills every RUNNING task in the registry, and
+/// the registry is one static shared by every test in this binary — so a test
+/// that sweeps and a test that is standing up a live task must not overlap, or
+/// the second one loses its child to the first one's quit. Both kinds hold this
+/// lock. (Poisoning is ignored on purpose: a panicking test has already failed,
+/// and turning that into a cascade of poisoned-lock failures hides which one.)
+#[cfg(test)]
+static SWEEP_ISOLATION: Mutex<()> = Mutex::new(());
+
+#[cfg(test)]
+fn sweep_isolation() -> std::sync::MutexGuard<'static, ()> {
+ SWEEP_ISOLATION.lock().unwrap_or_else(|e| e.into_inner())
+}
+
fn now_secs() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -278,28 +303,64 @@ pub(crate) async fn shell_task_start_impl(args: &Value) -> CmdResult {
}
});
- // The pid has to be read BEFORE the wait — `child.wait()` reaps the
- // process and `id()` then returns None, leaving nothing to walk.
- let child_pid = child.id();
- let wait_result = tokio::select! {
- res = child.wait() => Ok(res),
- _ = cancel_rx => Err(()),
- };
- let (exit_code, cancelled) = match wait_result {
- Ok(Ok(status)) => (status.code(), false),
- Ok(Err(_)) => (None, false),
- Err(_) => {
+ // REAPING THE CHILD FREES ITS PID, and the shutdown sweep kills by pid.
+ // Those two must never be able to interleave.
+ //
+ // `tokio::select! { child.wait() }` could not give us that: the reap
+ // happens inside the await, while `pid` stays in the registry until
+ // this task takes the lock again — which is only after both readers
+ // have drained, and a grandchild that inherited the pipe can keep them
+ // draining for minutes. Everything in that window was a kill aimed at a
+ // number the kernel had already handed to somebody else, and this
+ // module's tasks are `pnpm install` / `cargo build`, so "somebody else"
+ // is whatever the user started next.
+ //
+ // The reap is therefore a non-blocking `try_wait` performed while
+ // HOLDING the task lock, in the same critical section that clears the
+ // pid — and the sweep kills while holding that same lock (see
+ // `kill_all_background_tasks`). Either the sweep sees a pid that is
+ // still a live process, or it sees none. The price is one poll interval
+ // of latency on noticing the exit of a task that runs for minutes by
+ // design.
+ let mut cancel_rx = cancel_rx;
+ let (exit_code, cancelled) = loop {
+ let cancel_requested = tokio::select! {
+ biased;
+ _ = &mut cancel_rx => true,
+ _ = tokio::time::sleep(REAP_POLL) => false,
+ };
+ if cancel_requested {
+ // Nothing has reaped this child — this task is its only reaper
+ // and it is right here — so the pid still means what it meant
+ // at spawn. Take it out of the registry BEFORE the kill below
+ // reaps it, so the sweep cannot pick it up afterwards.
+ let pid = reader_inner.lock().unwrap().pid.take();
// `child.kill()` sends SIGKILL to the SHELL only. This module
// exists for `pnpm install` / `cargo build` — the commands with
// the deepest process trees — so cancelling used to leave the
// actual worker running detached, exactly the bug 743c310 fixed
// for the foreground shell tool. The Windows job object does not
// help here either: it fires when LU dies, not on a cancel.
- if let Some(pid) = child_pid {
+ if let Some(pid) = pid {
crate::commands::shell::kill_tree(pid);
}
let _ = child.kill().await;
- (None, true)
+ break (None, true);
+ }
+ let mut g = reader_inner.lock().unwrap();
+ match child.try_wait() {
+ Ok(Some(status)) => {
+ g.pid = None;
+ break (status.code(), false);
+ }
+ // Still running: keep the pid, it still addresses this process.
+ Ok(None) => {}
+ Err(_) => {
+ // We can no longer tell whether it is alive, so the pid is
+ // no longer safe to shoot at.
+ g.pid = None;
+ break (None, false);
+ }
}
};
// Wait for readers to drain so the tail is final.
@@ -312,8 +373,12 @@ pub(crate) async fn shell_task_start_impl(args: &Value) -> CmdResult {
g.status.finished_at = Some(now_secs());
g.status.output_tail = render_tail(&g.output_buf);
g.cancel_tx = None;
- // Drop the pid with the process: the OS may hand that number to a
- // stranger, and the shutdown sweep would then kill their tree.
+ // Already cleared above, in the same critical section as the reap —
+ // this only pins the invariant for any path that reaches here without
+ // going through the loop. Clearing it HERE was the whole bug: by this
+ // line the process has been reaped for as long as the readers took to
+ // drain, and the number has belonged to a stranger for just as long.
+ debug_assert!(g.pid.is_none(), "a finished task still carries a reaped pid");
g.pid = None;
});
@@ -364,35 +429,60 @@ pub(crate) async fn shell_task_kill_impl(args: &Value) -> CmdResult {
// On Windows only the tests reach it — the Job Object gets there first.
#[cfg_attr(target_os = "windows", allow(dead_code))]
pub(crate) fn kill_all_background_tasks() {
- let pids: Vec<u32> = {
+ let tasks: Vec<BgTask> = {
// try_lock, not lock: this also runs from the process-exit hook, where
// a thread that is holding the registry mutex may never be scheduled
// again. Losing the sweep beats hanging the quit.
let mut got = None;
for _ in 0..20 {
if let Ok(g) = REGISTRY.tasks.try_lock() {
- got = Some(
- g.iter()
- .filter_map(|t| {
- let inner = t.inner.try_lock().ok()?;
- inner.status.running.then_some(inner.pid).flatten()
- })
- .collect::<Vec<u32>>(),
- );
+ got = Some(g.iter().cloned().collect::<Vec<BgTask>>());
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
match got {
- Some(p) => p,
+ Some(t) => t,
None => return,
}
};
- for pid in pids {
- crate::commands::shell::kill_tree(pid);
+ for task in tasks {
+ // Kill while HOLDING the task's own lock, rather than collecting pids
+ // and firing afterwards. That lock is what makes the pid mean anything:
+ // the reader task reaps and clears the pid inside the same critical
+ // section, so a pid read here cannot be freed — and handed to a
+ // stranger — before the kill goes out. Reading it and releasing first
+ // reopened exactly the window this is closing.
+ let inner = match lock_briefly(&task) {
+ Some(g) => g,
+ None => continue,
+ };
+ if !inner.status.running {
+ continue;
+ }
+ // Read, do not take: the reader task is the one that clears the pid,
+ // and it does so in the same breath as the reap. Holding the lock is
+ // what makes the number valid here; removing it would only hide the
+ // task from a second sweep, which is already harmless.
+ if let Some(pid) = inner.pid {
+ crate::commands::shell::kill_tree(pid);
+ }
}
}
+/// `try_lock` with a short retry — same reasoning as the registry lock above:
+/// never block the quit forever, but do not give up on the first contention
+/// either (the reader task holds this lock for a `try_wait` at a time).
+fn lock_briefly(task: &BgTask) -> Option<std::sync::MutexGuard<'_, BgTaskInner>> {
+ for _ in 0..20 {
+ if let Ok(g) = task.inner.try_lock() {
+ return Some(g);
+ }
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ }
+ None
+}
+
/// Run the sweep when the process exits.
///
/// Every quit path ends in `exit()` — the tray Quit, `exit_app`, the updater,
@@ -582,6 +672,7 @@ mod cancel_tests {
#[tokio::test]
#[cfg_attr(target_os = "windows", ignore = "uses sh/ps")]
async fn cancelling_takes_the_grandchild_with_it() {
+ let _isolation = super::sweep_isolation();
// The shell prints its grandchild's pid, then waits on it.
let start = shell_task_start_impl(&json!({
"command": "sleep 30 & echo $! ; wait",
@@ -639,6 +730,7 @@ mod shutdown_sweep_tests {
#[tokio::test]
#[cfg_attr(target_os = "windows", ignore = "uses sh/ps; Windows has the Job Object")]
async fn quitting_takes_a_running_task_and_its_children_with_it() {
+ let _isolation = super::sweep_isolation();
let start = shell_task_start_impl(&json!({
"command": "sleep 30 & echo $! ; wait",
"shell": "sh",
@@ -676,11 +768,84 @@ mod shutdown_sweep_tests {
}
}
+ /// Is this number still a process — zombie included?
+ ///
+ /// `alive()` above reports a zombie as dead, which is the wrong question
+ /// here: a zombie has NOT been reaped, so its pid is still reserved. What
+ /// matters for the sweep is the moment the kernel is free to hand the
+ /// number out again, and that is the moment `ps` stops listing it at all.
+ #[cfg(unix)]
+ fn in_process_table(pid: u32) -> bool {
+ std::process::Command::new("ps")
+ .args(["-o", "pid=", "-p", &pid.to_string()])
+ .output()
+ .map(|o| !String::from_utf8_lossy(&o.stdout).trim().is_empty())
+ .unwrap_or(false)
+ }
+
+ /// The window the reaping fix closes.
+ ///
+ /// `child.wait()` reaps, and from that instant the pid may be reused. The
+ /// pid was cleared much later — after both output readers had drained —
+ /// and a grandchild that inherited stdout keeps them draining for as long
+ /// as it lives. So: shell exits immediately, grandchild holds the pipe, and
+ /// for the next three seconds the registry kept handing the sweep a number
+ /// that belonged to whatever the kernel gave it to next.
+ #[tokio::test]
+ #[cfg_attr(target_os = "windows", ignore = "uses sh/ps")]
+ #[cfg(unix)]
+ async fn a_reaped_pid_is_gone_from_the_registry_the_instant_it_is_freed() {
+ let _isolation = super::sweep_isolation();
+ let start = shell_task_start_impl(&json!({
+ // The shell exits at once; the grandchild inherits stdout and keeps
+ // the reader task running long after the shell has been reaped.
+ "command": "sleep 3 & exit 0",
+ "shell": "sh",
+ }))
+ .await
+ .expect("start");
+ let id = start["id"].as_str().expect("id").to_string();
+
+ let task = REGISTRY.get(&id).expect("the task is in the registry");
+ let shell_pid = task
+ .inner
+ .lock()
+ .unwrap()
+ .pid
+ .expect("a running task must carry its pid");
+
+ // Wait for the kernel to release the number — i.e. for the reap.
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
+ while in_process_table(shell_pid) {
+ assert!(
+ std::time::Instant::now() < deadline,
+ "the shell ({shell_pid}) never exited, so there is nothing to prove",
+ );
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+
+ // The reader is still draining the grandchild's pipe, so the task is
+ // still marked running — and that is exactly when the sweep would fire.
+ // Read the state out and release the lock BEFORE asserting: a panic
+ // holding this guard poisons the shared registry and every other test
+ // in the binary fails on the poison instead of on its own subject.
+ let (still_listed, running) = {
+ let inner = task.inner.lock().unwrap();
+ (inner.pid, inner.status.running)
+ };
+ assert!(
+ still_listed.is_none(),
+ "the registry still hands out {shell_pid}, which the kernel has already freed \
+ (running={running})",
+ );
+ }
+
/// A finished task's pid may already belong to somebody else — the sweep
/// must never fire at it. Sweeping an idle registry must also not panic.
#[tokio::test]
#[cfg_attr(target_os = "windows", ignore = "uses sh")]
async fn a_finished_task_is_not_swept() {
+ let _isolation = super::sweep_isolation();
let start = shell_task_start_impl(&json!({ "command": "true", "shell": "sh" }))
.await
.expect("start");
diff --git a/src-tauri/src/commands/filesystem.rs b/src-tauri/src/commands/filesystem.rs
index e19a9f3c..a6960593 100644
--- a/src-tauri/src/commands/filesystem.rs
+++ b/src-tauri/src/commands/filesystem.rs
@@ -104,18 +104,32 @@ fn is_within(root: &Path, cand: &Path) -> bool {
}
/// Jail `candidate` to `root`: return the normalized path when it stays inside
-/// `root`, otherwise an error. This is the single containment boundary for
-/// every agent/remote file op — it stops a prompt-injected model or a remote
-/// client from reading `~/.ssh/id_rsa`, writing into `\Startup\`, or `..`-ing
-/// out of the workspace. Absolute paths are allowed ONLY when they fall within
-/// `root`, so the desktop coding agent can still use absolute paths inside the
-/// user-picked project folder (#62).
+/// `root`, otherwise an error. Absolute paths are allowed ONLY when they fall
+/// within `root`, so the desktop coding agent can still use absolute paths
+/// inside the user-picked project folder (#62).
///
/// The DECISION is made on symlink-resolved paths, the RETURNED path is the
/// lexical one the caller asked for: canonicalize() hands back `\\?\C:\…` on
/// Windows and `/private/var/…` on macOS, and that string is echoed to the UI
-/// and compared in the frontend. Opening the lexical path is equivalent —
-/// its link target was just proven to be inside the root.
+/// and compared in the frontend.
+///
+/// What this actually guarantees, and what it does not:
+///
+/// * It answers ONE question — does this path string, with `..` resolved and
+/// with the symlinks of its deepest existing ancestor followed, stay under
+/// `root`. That is enough for the traversal shapes a prompt-injected model
+/// sends (`../../.ssh/id_rsa`) and for a symlink planted inside the
+/// workspace, which is what `resolve_existing_prefix` is for.
+/// * It is a path check, not a permission check. Whether the caller-supplied
+/// ROOT may be a jail at all is `check_workspace_root`'s question, and
+/// nothing here asks it.
+/// * The check and the later `open()` are separate syscalls on a filesystem
+/// other processes can write. A component replaced by a symlink in between
+/// escapes it (TOCTOU); so does a hard link inside the workspace pointing at
+/// a file outside, which is indistinguishable from the file itself. Closing
+/// those needs `openat`/`O_NOFOLLOW` on a directory handle, not a string
+/// comparison — the workspace is assumed not to be attacker-writable while
+/// an operation is in flight.
pub(crate) fn contain_within(root: &Path, candidate: &Path) -> Result<PathBuf, String> {
let nroot = lexical_normalize(root);
let ncand = lexical_normalize(candidate);
@@ -178,19 +192,101 @@ pub(crate) fn workspace_root(chat_id: Option<&str>, working_dir: Option<&str>) -
dirs::home_dir().unwrap_or_default().join("agent-workspace").join(slug)
}
-/// Folders the user picked in a native dialog this run. A registered root is
-/// trusted verbatim; everything else has to pass `check_workspace_root`.
-static PICKED_ROOTS: Lazy<Mutex<Vec<PathBuf>>> = Lazy::new(|| Mutex::new(Vec::new()));
+/// THE ALLOWLIST: folders the user chose in a native folder dialog.
+///
+/// Kept on disk, because a pick is a decision about a project and not about a
+/// run: the workspace the user selected last week arrives from the frontend's
+/// persisted state on the next launch, and an in-memory list would refuse it
+/// and force a re-pick every single start.
+///
+/// The file is only ever written from `remember_picked_root`, i.e. from the
+/// native dialog, and every entry is re-checked against
+/// `may_be_a_picked_root` when it is read back — an edited file cannot add `/`
+/// or `~/.ssh` to the allowlist.
+static PICKED_ROOTS: Lazy<Mutex<Vec<PathBuf>>> = Lazy::new(|| Mutex::new(load_picked_roots()));
+
+fn picked_roots_file() -> PathBuf {
+ crate::os_paths::data_dir().join("workspace-roots.json")
+}
+
+fn load_picked_roots() -> Vec<PathBuf> {
+ load_roots_from(&picked_roots_file())
+}
+
+/// Read the allowlist back, re-checking every entry.
+///
+/// The file is data, not authority: a corrupted or edited one may shrink the
+/// allowlist but must not be able to grow it past what a dialog could have
+/// produced — so `/` or `~/.ssh` in the file is dropped on the way in, exactly
+/// as a click on them would have been.
+fn load_roots_from(file: &Path) -> Vec<PathBuf> {
+ let raw = fs::read_to_string(file).unwrap_or_default();
+ serde_json::from_str::<Vec<String>>(&raw)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|s| lexical_normalize(Path::new(&s)))
+ .filter(|p| may_be_a_picked_root(p).is_ok())
+ .collect()
+}
+
+fn save_picked_roots(roots: &[PathBuf]) {
+ save_roots_to(&picked_roots_file(), roots)
+}
+
+fn save_roots_to(file: &Path, roots: &[PathBuf]) {
+ let list: Vec<String> = roots.iter().map(|p| p.to_string_lossy().to_string()).collect();
+ let Ok(json) = serde_json::to_string_pretty(&list) else { return };
+ if let Some(parent) = file.parent() {
+ let _ = fs::create_dir_all(parent);
+ }
+ let _ = fs::write(file, json);
+}
+
+/// Test-only stand-in for the native dialog.
+///
+/// Same gate as `remember_picked_root` — a root a real pick could not produce
+/// is rejected here too — but it does not persist: a test run must not write
+/// its temp folders into the user's real allowlist.
+#[cfg(test)]
+pub(crate) fn allow_root_for_test(root: &Path) {
+ let norm = lexical_normalize(root);
+ may_be_a_picked_root(&norm).expect("a test root must be a folder a pick could produce");
+ let mut roots = PICKED_ROOTS.lock().expect("allowlist");
+ if !roots.iter().any(|r| r == &norm) {
+ roots.push(norm);
+ }
+}
/// Record a folder the USER chose in a native dialog as a legitimate workspace
-/// root. Called by `set_chat_workspace_override` (the Remote dispatch picker).
-pub(crate) fn remember_picked_root(root: &Path) {
+/// root. The ONE caller is `system::pick_folder` — the dialog itself.
+///
+/// It must stay that way. Recording is what makes a folder a jail root, so a
+/// command the WebView can call with a path of its choosing (that is what
+/// `set_chat_workspace_override` is) must never record: it would hand the
+/// allowlist back to the caller it exists to constrain. Those callers
+/// VALIDATE against the list instead (`validate_workspace_root`).
+///
+/// Returns an error for the handful of folders that are not workspaces even
+/// when a human clicked them; see `may_be_a_picked_root`.
+pub(crate) fn remember_picked_root(root: &Path) -> Result<(), String> {
let norm = lexical_normalize(root);
+ may_be_a_picked_root(&norm)?;
if let Ok(mut roots) = PICKED_ROOTS.lock() {
if !roots.iter().any(|r| r == &norm) {
roots.push(norm);
+ save_picked_roots(&roots);
}
}
+ Ok(())
+}
+
+/// The app's OWN working directories — the per-chat sandboxes under
+/// `~/agent-workspace/`. They are roots nobody picks in a dialog because the
+/// app derives them itself (`workspace_root`), so the allowlist has to know
+/// them or a plain sandbox chat could not read its own files.
+fn is_app_work_dir(norm: &Path) -> bool {
+ let base = lexical_normalize(&dirs::home_dir().unwrap_or_default().join("agent-workspace"));
+ is_within(&base, norm)
}
/// Directories that are never a project workspace, only a target.
@@ -258,60 +354,97 @@ fn named_depth(p: &Path) -> usize {
.count()
}
-/// Is this frontend-supplied path allowed to BE a jail root?
-///
-/// `contain_within` only ever answered "does the path stay inside the root" —
-/// the root itself arrived from the WebView on every call and was taken on
-/// faith, so `fs_read("/etc/shadow", null, "/")` passed containment perfectly
-/// and read the file. The jail was only ever as narrow as the string the caller
-/// chose for it.
+/// The folders that may never be a jail root, however they got proposed.
///
-/// A root is accepted when the user picked it in a native dialog (see
-/// `remember_picked_root`), or, failing that, when it is structurally a project
-/// folder: deep enough not to be a drive or filesystem root, not a container of
-/// other people's homes, and not inside a system or credential directory. The
-/// structural fallback exists because `system::pick_folder` — the one dialog
-/// every folder choice goes through — does not register its result yet; without
-/// it, enforcing the allowlist alone would refuse every workspace the user
-/// picked in an earlier session.
-fn check_workspace_root(root: &Path) -> Result<(), String> {
- let norm = lexical_normalize(root);
- if let Ok(roots) = PICKED_ROOTS.lock() {
- if roots.iter().any(|r| is_within(r, &norm)) {
- return Ok(());
- }
- }
+/// Second gate, not the first one: `check_workspace_root` decides membership of
+/// the allowlist, this decides whether the member is a sane workspace at all. A
+/// dialog click is consent to expose ONE project folder; the dialog opens
+/// wherever it was last pointed, and one mis-click on `$HOME`, `/Volumes` or
+/// `~/.ssh` would otherwise turn "the agent may work in this folder" into "the
+/// agent may read every credential on the machine" — permanently, because the
+/// pick is remembered.
+fn may_be_a_picked_root(norm: &Path) -> Result<(), String> {
let refuse = |why: &str| {
Err(format!(
"Not an allowed workspace folder ({}): {}",
why,
- root.display()
+ norm.display()
))
};
- // `D:\Projects` is an ordinary Windows layout and only one component deep;
- // on Unix the same depth is `/etc` or `/var`, which is not.
- let min_depth = if cfg!(windows) { 1 } else { 2 };
- if named_depth(&norm) < min_depth {
+ // `/` and `C:\` have no named component at all.
+ if named_depth(norm) == 0 {
return refuse("a drive or filesystem root is not a workspace");
}
// Mutual containment == equality, and it stays case-insensitive on Windows
// the way every other comparison in this file is.
let same = |a: &Path, b: &Path| is_within(a, b) && is_within(b, a);
for bad in forbidden_exact_roots() {
- if same(&lexical_normalize(&bad), &norm) {
+ if same(&lexical_normalize(&bad), norm) {
return refuse("a home or mount container is not a workspace");
}
}
for bad in forbidden_root_prefixes() {
- if is_within(&lexical_normalize(&bad), &norm) {
+ if is_within(&lexical_normalize(&bad), norm) {
return refuse("system or credential directory");
}
}
Ok(())
}
+/// Is this frontend-supplied path allowed to BE a jail root?
+///
+/// `contain_within` only ever answered "does the path stay inside the root" —
+/// the root itself arrived from the WebView on every call and was taken on
+/// faith, so `fs_read("/etc/shadow", null, "/")` passed containment perfectly
+/// and read the file. The jail was only ever as narrow as the string the caller
+/// chose for it.
+///
+/// This is an ALLOWLIST, and it has to be one. The threat model this package
+/// writes down in `capabilities/default.json` is a script-execution bug in the
+/// WebView — a compromised renderer calling the IPC commands with arguments of
+/// its choosing. Against that caller a deny-list is the wrong shape: it has to
+/// enumerate every directory worth stealing on three operating systems, and one
+/// omission (`~/.mozilla`, `~/.thunderbird`, `~/Library/Messages`, a password
+/// manager's export folder, the user's whole `Documents`) is a full read of it.
+/// A renderer cannot open a native folder dialog and click in it, so the list of
+/// folders a human picked there is a boundary it cannot cross at all.
+///
+/// Two gates, in this order:
+/// 1. the allowlist — an app work dir, or a folder the user picked in the
+/// native dialog (this run or an earlier one; see `PICKED_ROOTS`);
+/// 2. `may_be_a_picked_root` — the handful of folders that are not a
+/// workspace even when a human clicked them.
+///
+/// Upgrade note: a workspace picked by a build older than this one was never
+/// recorded, so the first use after the update is refused until the user picks
+/// the folder again. That is one dialog, once, per folder — the alternative is
+/// trusting a path the WebView sent us, which is the hole being closed.
+fn check_workspace_root(root: &Path) -> Result<(), String> {
+ let norm = lexical_normalize(root);
+ if is_app_work_dir(&norm) {
+ return Ok(());
+ }
+ let picked = PICKED_ROOTS
+ .lock()
+ .map(|roots| roots.iter().any(|r| is_within(r, &norm)))
+ .unwrap_or(false);
+ if !picked {
+ return Err(format!(
+ "Not an allowed workspace folder (only a folder you chose in LU's folder picker \
+ can be a workspace — pick it again to allow it): {}",
+ root.display()
+ ));
+ }
+ may_be_a_picked_root(&norm)
+}
+
/// `check_workspace_root` for callers outside this module (the Remote dispatch
/// folder picker validates the folder before storing it as an override).
+///
+/// Validate, never record: the path these callers hold came over IPC from the
+/// WebView, and a caller that could add its own argument to the allowlist would
+/// be the hole the allowlist exists to close. Only `system::pick_folder` — the
+/// native dialog — records.
pub(crate) fn validate_workspace_root(root: &Path) -> Result<(), String> {
check_workspace_root(root)
}
@@ -798,7 +931,8 @@ pub async fn save_binary_file_dialog(
#[cfg(test)]
mod tests {
- use super::{is_workspace_root_path, normalize_to_existing_style, resolve_path};
+ use super::{allow_root_for_test, is_workspace_root_path, normalize_to_existing_style, resolve_path};
+ use std::path::Path;
// ── #11: fs_write preserves the existing file's EOL + BOM convention ──
#[test]
@@ -894,6 +1028,7 @@ mod tests {
// ── #62: relative paths must honor the folder workspace ──────────
#[test]
fn relative_path_resolves_against_working_dir() {
+ allow_root_for_test(Path::new("D:/Projects/site"));
let got = resolve_path("src/main.rs", Some("chat-1"), Some("D:/Projects/site")).unwrap();
let s = got.to_string_lossy().replace('\\', "/");
assert_eq!(s, "D:/Projects/site/src/main.rs");
@@ -921,6 +1056,7 @@ mod tests {
} else {
("/projects/site", "/projects/site/src/main.rs")
};
+ allow_root_for_test(Path::new(root));
let got = resolve_path(abs, Some("chat-1"), Some(root)).unwrap();
let s = got.to_string_lossy().replace('\\', "/");
assert_eq!(s, abs);
@@ -940,6 +1076,7 @@ mod tests {
#[test]
fn dotdot_traversal_out_of_working_dir_is_rejected() {
+ allow_root_for_test(Path::new("D:/Projects/site"));
assert!(resolve_path("../../secret.txt", Some("c"), Some("D:/Projects/site")).is_err());
}
@@ -1060,6 +1197,7 @@ mod jail_adversarial_tests {
fs::create_dir_all(&ws).unwrap();
fs::write(base.join("secret.txt"), b"private").unwrap();
fs::write(ws.join("inside.txt"), b"ok").unwrap();
+ allow_root_for_test(&ws); // stands in for the user picking this folder
let wd = Some(ws.to_string_lossy().to_string());
// `*` matches dotfiles too (require_literal_leading_dot is false), so
@@ -1136,6 +1274,9 @@ mod workspace_root_guard_tests {
roots.push("/Volumes/Work/site".to_string());
}
for root in roots {
+ // Each one stands for a folder the user chose in the dialog — the
+ // only way any of them becomes a workspace now.
+ allow_root_for_test(Path::new(&root));
assert!(
resolve_path("src/main.rs", Some("c"), Some(&root)).is_ok(),
"root {root:?} was refused",
@@ -1149,7 +1290,7 @@ mod workspace_root_guard_tests {
fn a_folder_the_user_picked_is_trusted() {
let odd = std::env::temp_dir().join(format!("lu-picked-{}", std::process::id()));
let _ = fs::create_dir_all(&odd);
- remember_picked_root(&odd);
+ allow_root_for_test(&odd);
let root = odd.to_string_lossy().to_string();
assert!(resolve_path("notes.md", None, Some(&root)).is_ok());
// Registering a root does NOT widen the jail inside it.
@@ -1182,6 +1323,7 @@ mod workspace_root_guard_tests {
fn a_file_that_does_not_exist_yet_still_resolves() {
let ws = std::env::temp_dir().join(format!("lu-newfile-{}", std::process::id()));
let _ = fs::create_dir_all(&ws);
+ allow_root_for_test(&ws);
let root = ws.to_string_lossy().to_string();
let got = resolve_path("deep/new/dir/notes.md", None, Some(&root)).expect("new path");
assert!(got.ends_with("deep/new/dir/notes.md"), "got: {got:?}");
@@ -1202,6 +1344,7 @@ mod workspace_root_guard_tests {
fs::create_dir_all(&outside).unwrap();
fs::write(outside.join("secret.txt"), b"private").unwrap();
std::os::unix::fs::symlink(&outside, ws.join("escape")).unwrap();
+ allow_root_for_test(&ws);
let root = ws.to_string_lossy().to_string();
assert!(
@@ -1223,6 +1366,179 @@ mod workspace_root_guard_tests {
}
}
+/// The workspace root is an ALLOWLIST, not a deny-list.
+///
+/// The old guard accepted any path that LOOKED like a project folder. Under the
+/// threat model this package writes down — a script-execution bug in the
+/// WebView calling the IPC commands with arguments of its choosing — that is
+/// the wrong shape: `~/Documents`, `~/.mozilla`, a password manager's export
+/// folder and a mounted backup disk all look exactly like a project folder, and
+/// a deny-list has to name every one of them on three operating systems to hold.
+#[cfg(test)]
+mod workspace_allowlist_tests {
+ use super::*;
+
+ fn unique(tag: &str) -> PathBuf {
+ std::env::temp_dir().join(format!("lu-allow-{}-{}-{:?}", tag, std::process::id(), std::thread::current().id()))
+ }
+
+ #[test]
+ fn a_folder_nobody_picked_is_refused_however_ordinary_it_looks() {
+ // Structurally impeccable: deep, under the user's home, not a system or
+ // credential directory, not a mount container. The deny-list guard
+ // accepted it — and this is where the interesting files are.
+ let home = dirs::home_dir().unwrap_or_default();
+ for never_picked in [
+ home.join("Documents").join("Tax-2026"),
+ home.join("Desktop"),
+ home.join("Downloads").join("statements"),
+ ] {
+ let s = never_picked.to_string_lossy().to_string();
+ let got = check_workspace_root(&never_picked);
+ assert!(got.is_err(), "{never_picked:?} was accepted without anyone picking it");
+ // And the whole file API is closed for it, not just the predicate.
+ assert!(
+ resolve_path("passport.pdf", Some("c"), Some(&s)).is_err(),
+ "{never_picked:?} still resolved a file op",
+ );
+ }
+ }
+
+ #[test]
+ fn a_folder_the_user_picked_in_the_dialog_becomes_a_root() {
+ let dir = unique("picked");
+ let _ = fs::create_dir_all(&dir);
+ assert!(check_workspace_root(&dir).is_err(), "the test root was allowed before the pick");
+ allow_root_for_test(&dir);
+ assert!(check_workspace_root(&dir).is_ok(), "a picked folder was refused");
+ // Subfolders of a picked root are roots too — the same project.
+ assert!(check_workspace_root(&dir.join("packages").join("api")).is_ok());
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn the_apps_own_sandbox_is_a_root_without_anyone_picking_it() {
+ // The per-chat sandbox is derived, never chosen, so the allowlist has
+ // to know it or a plain sandbox chat cannot read its own files.
+ let sandbox = workspace_root(Some("chat-1"), None);
+ assert!(check_workspace_root(&sandbox).is_ok(), "the agent sandbox is not a root");
+ }
+
+ #[test]
+ fn even_a_dialog_click_cannot_make_the_home_directory_a_workspace() {
+ // The dialog opens wherever it was last pointed. One mis-click on $HOME
+ // or a credential store must not turn "work in this folder" into "read
+ // every secret on the machine" — permanently, because picks are kept.
+ let home = dirs::home_dir().unwrap_or_default();
+ for bad in [home.clone(), home.join(".ssh"), home.join(".aws"), PathBuf::from("/")] {
+ assert!(
+ remember_picked_root(&bad).is_err(),
+ "{bad:?} was recorded as a workspace root",
+ );
+ assert!(check_workspace_root(&bad).is_err(), "{bad:?} passed as a root");
+ }
+ }
+
+ #[test]
+ fn a_tampered_allowlist_file_cannot_grant_what_a_dialog_could_not() {
+ // The file is data, not authority.
+ let dir = unique("file");
+ let _ = fs::create_dir_all(&dir);
+ let file = dir.join("workspace-roots.json");
+ let home = dirs::home_dir().unwrap_or_default();
+ let good = dir.join("project");
+ let payload = serde_json::to_string(&vec![
+ "/".to_string(),
+ home.to_string_lossy().to_string(),
+ home.join(".ssh").to_string_lossy().to_string(),
+ good.to_string_lossy().to_string(),
+ ])
+ .unwrap();
+ fs::write(&file, payload).unwrap();
+
+ let loaded = load_roots_from(&file);
+ assert_eq!(loaded, vec![lexical_normalize(&good)], "a forbidden root survived the read");
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn a_pick_survives_a_restart() {
+ // Why the list is on disk at all: the frontend keeps the last workspace
+ // and sends it again on the next launch. An in-memory allowlist would
+ // refuse it and demand a fresh pick on every single start.
+ let dir = unique("restart");
+ let _ = fs::create_dir_all(&dir);
+ let file = dir.join("workspace-roots.json");
+ let project = dir.join("site");
+ save_roots_to(&file, &[lexical_normalize(&project)]);
+ assert_eq!(load_roots_from(&file), vec![lexical_normalize(&project)]);
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn a_missing_or_corrupt_allowlist_file_is_an_empty_allowlist() {
+ // Fail CLOSED: no file, or garbage in it, must not mean "allow anything".
+ let dir = unique("corrupt");
+ let _ = fs::create_dir_all(&dir);
+ assert!(load_roots_from(&dir.join("nope.json")).is_empty());
+ let file = dir.join("workspace-roots.json");
+ fs::write(&file, b"{ not json").unwrap();
+ assert!(load_roots_from(&file).is_empty());
+ let _ = fs::remove_dir_all(&dir);
+ }
+}
+
+/// The two file tools that block for seconds run OFF the Tauri main thread.
+#[cfg(test)]
+mod off_main_thread_tests {
+ const FILESYSTEM_RS: &str = include_str!("filesystem.rs");
+
+ /// The attributes and doc comment directly above `sig`.
+ fn preamble_of(sig: &str) -> &'static str {
+ let at = FILESYSTEM_RS.find(sig).unwrap_or_else(|| panic!("{sig} is gone"));
+ let head = &FILESYSTEM_RS[..at];
+ let start = head.rfind("\n\n").map(|i| i + 2).unwrap_or(0);
+ &head[start..]
+ }
+
+ /// `fs_search` walks eight directory levels and reads every file under a
+ /// megabyte — seconds of blocking IO on a real repo, and as a plain
+ /// `#[tauri::command]` every one of those seconds was spent on the main
+ /// thread with the window frozen.
+ ///
+ /// This is a source guard, and deliberately so: the fix is which attribute
+ /// Tauri's macro sees. It changes how the COMMAND is dispatched, not what
+ /// the Rust function does, so no in-process call can observe it — awaiting
+ /// `fs_search` from a test runs the same code either way. The attribute is
+ /// pinned instead, on this function, so dropping it fails here rather than
+ /// in a bug report about a frozen window.
+ #[test]
+ fn fs_search_is_dispatched_off_the_main_thread() {
+ let pre = preamble_of("pub fn fs_search(");
+ assert!(
+ pre.contains("#[tauri::command(async)]"),
+ "fs_search lost its off-main-thread dispatch: {pre}",
+ );
+ assert!(
+ !pre.contains("#[tauri::command]"),
+ "fs_search is back on the plain (main-thread) command attribute: {pre}",
+ );
+ }
+
+ /// The guard on the guard: `preamble_of` must return the attributes of the
+ /// function asked for and not the whole file.
+ #[test]
+ fn the_preamble_slicer_reads_one_signature() {
+ let pre = preamble_of("pub fn fs_search(");
+ assert!(pre.len() < 2_000, "the slice ran past the attribute block");
+ assert!(!pre.contains("pub fn fs_info("), "the slice ran into another function");
+ // fs_read takes the other route to the same place: an `async fn` that
+ // hands the blocking work to spawn_blocking.
+ assert!(preamble_of("pub async fn fs_read(").contains("#[tauri::command]"));
+ assert!(FILESYSTEM_RS.contains("spawn_blocking(move || fs_read_sync("));
+ }
+}
+
#[cfg(test)]
mod binary_read_tests {
use super::*;
@@ -1232,6 +1548,7 @@ mod binary_read_tests {
let d = std::env::temp_dir().join(format!("lu-fsread-{}-{}", tag, std::process::id()));
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(&d).unwrap();
+ allow_root_for_test(&d); // stands in for the user picking this folder
d
}
@@ -1304,6 +1621,7 @@ mod explorer_byte_read_tests {
let d = std::env::temp_dir().join(format!("lu-fsbytes-{}-{}", tag, std::process::id()));
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(&d).unwrap();
+ allow_root_for_test(&d); // stands in for the user picking this folder
d
}
diff --git a/src-tauri/src/commands/oauth.rs b/src-tauri/src/commands/oauth.rs
index 7d0926b5..27fdf399 100644
--- a/src-tauri/src/commands/oauth.rs
+++ b/src-tauri/src/commands/oauth.rs
@@ -77,15 +77,37 @@ enum Verdict {
/// `<iframe>` pointed at the same URL. Absent (pre-2023 Safari, a non-
/// browser client) they simply do not vote.
///
-/// `state` is deliberately not checked, and this is the one hole left: the
-/// Supabase PKCE redirect carries `code` alone, so the only way to bind a
-/// per-attempt nonce would be to add a query parameter to the redirect URI —
-/// which the server's exact-match `uri_allow_list` would then refuse,
-/// breaking sign-in for everyone. What remains reachable after the checks
-/// above is a top-level navigation the attacker cannot make silently: a
-/// `window.open`/form submit needs a user gesture and opens a visible window.
-/// A code from a stranger is useless in any case — the PKCE verifier never
-/// leaves the app, so the exchange fails.
+/// KNOWN LIMITATION, stated plainly because the version of this comment that
+/// stood here was wrong and wrong in the reassuring direction.
+///
+/// It claimed that what survives the checks above "needs a user gesture and
+/// opens a visible window". It does not. `location.href = "http://127.0.0.1:
+/// 17872/callback?error=…"`, a `<meta http-equiv="refresh">` and a server-side
+/// 302 are all TOP-LEVEL navigations, any page the user already has open can
+/// start one with no gesture and nothing visible, and the browser sends exactly
+/// the shape this function accepts: `GET /callback`, the loopback `Host`, no
+/// `Origin`, `Sec-Fetch-Mode: navigate`, `Sec-Fetch-Dest: document`. Nothing in
+/// the request distinguishes it from Supabase's redirect.
+///
+/// So, while a sign-in is pending, any open tab can end the wait and choose the
+/// text the user is then shown. What it CANNOT do is sign anyone in: the PKCE
+/// verifier never leaves the app, so a stranger's `code` fails the exchange —
+/// the residual is a denial of the sign-in plus attacker-chosen text, and
+/// src/api/cloud/supabase.ts (`providerErrorText`) is what keeps that text from
+/// posing as LU's own words. `a_scripted_top_level_navigation_…` below pins the
+/// limitation so it stays visible.
+///
+/// What would actually close it is a per-attempt `state` nonce, and it cannot
+/// be built here alone: the Supabase PKCE redirect carries `code` alone, so the
+/// nonce would have to ride on the redirect URI as a query parameter
+/// (`…/callback?state=<nonce>`) — and that URI is matched against the Supabase
+/// project's `uri_allow_list`, which holds the three ladder URIs as EXACT
+/// entries. A redirect URI with a query would not match, GoTrue would fall back
+/// to the site URL, and sign-in would break for everyone. Making the nonce
+/// possible is a server-side change to that allow-list (see the note in the
+/// changelog); until it happens there is no half-measure worth adding here,
+/// because a nonce this listener generates but the redirect never carries is
+/// dead code that only looks like a defence.
fn classify(req: &str, port: u16) -> Verdict {
let mut lines = req.lines();
let Some(request_line) = lines.next() else {
@@ -389,6 +411,43 @@ mod tests {
assert_eq!(classify(&req, PORT), Verdict::Reject);
}
+ /// THE RESIDUAL, pinned rather than described.
+ ///
+ /// `location.href = …` from any open tab produces this request — no user
+ /// gesture, no visible window, and byte for byte what Supabase's 302
+ /// produces. It is accepted, and it has to be: nothing in a top-level
+ /// navigation says who started it. Only a per-attempt `state` nonce
+ /// separates them, and the nonce needs a redirect URI with a query
+ /// parameter, which the Supabase project's exact-match `uri_allow_list`
+ /// refuses (see `classify`).
+ ///
+ /// This test therefore documents a limitation, not a guarantee. When the
+ /// allow-list gains an entry that tolerates `?state=`, this is the test
+ /// that must flip to `Reject` — and it will fail until someone does.
+ #[test]
+ fn a_scripted_top_level_navigation_is_indistinguishable_from_the_real_redirect() {
+ let scripted = format!(
+ "GET /callback?error=access_denied&error_description=Your+account+was+closed HTTP/1.1\r\n\
+ Host: 127.0.0.1:{PORT}\r\n\
+ Upgrade-Insecure-Requests: 1\r\n\
+ Accept: text/html,application/xhtml+xml\r\n\
+ Sec-Fetch-Site: cross-site\r\n\
+ Sec-Fetch-Mode: navigate\r\n\
+ Sec-Fetch-Dest: document\r\n\
+ Connection: close\r\n\r\n"
+ );
+ // Identical to what the provider's redirect sends — same method, same
+ // path, same Host, no Origin, same Sec-Fetch triple.
+ assert_eq!(
+ classify(&scripted, PORT),
+ classify(
+ &real_redirect("error=access_denied&error_description=Your+account+was+closed"),
+ PORT
+ ),
+ "the two are distinguishable now — if that is a `state` check, this test is stale",
+ );
+ }
+
// ── strays that must not end the attempt either ─────────────────────
#[test]
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rs
index 02fb2db3..629f814f 100644
--- a/src-tauri/src/commands/remote.rs
+++ b/src-tauri/src/commands/remote.rs
@@ -4887,9 +4887,48 @@ async fn handle_qr(AxumState(state): AxumState<RemoteState>) -> Json<QrResponse>
// ─── Devices ───
-async fn handle_devices(AxumState(state): AxumState<RemoteState>) -> Json<Vec<ConnectedDevice>> {
- let devices = state.connected_devices.lock().await;
- Json(devices.clone())
+/// The connected-device list as a stand-alone axum sub-state.
+///
+/// The two handlers below need nothing from `RemoteState` except this list, and
+/// `RemoteState` carries an `AppHandle` — which cannot be built in a unit test.
+/// Extracting the list instead of the whole state is what makes the handler
+/// BODIES (the caller check, the filtering) reachable from a test rather than
+/// only the helpers they call: a gegenprüfer who reverts a handler to its old
+/// body must see a red test, and that only works if the test runs the handler.
+#[derive(Clone)]
+struct DeviceRegistry(Arc<TokioMutex<Vec<ConnectedDevice>>>);
+
+impl axum::extract::FromRef<RemoteState> for DeviceRegistry {
+ fn from_ref(state: &RemoteState) -> Self {
+ DeviceRegistry(state.connected_devices.clone())
+ }
+}
+
+/// Show the caller its OWN row, and only that one.
+///
+/// "Authenticated" is not the only rung on this ladder any more (see
+/// `handle_disconnect` for the same class). This endpoint used to hand every
+/// paired phone the full list: the id, the LAN/public IP and the user agent of
+/// every OTHER device paired with this desktop. The id is the interesting part
+/// — it is the `sub` of the other device's session and was, until the fix below,
+/// all it took to end that session. The desktop's own list is not served over
+/// HTTP at all (`remote_connected_devices`, a Tauri command), so nothing that
+/// legitimately needs the full roster loses it here.
+fn own_device_rows(devices: &[ConnectedDevice], caller_id: &str) -> Vec<ConnectedDevice> {
+ devices.iter().filter(|d| d.id == caller_id).cloned().collect()
+}
+
+async fn handle_devices(
+ AxumState(DeviceRegistry(devices)): AxumState<DeviceRegistry>,
+ caller: Option<axum::Extension<CallerDevice>>,
+) -> Response {
+ // Set by auth_middleware on everything that got past it; this route is
+ // behind it, so a missing one means the caller was never identified.
+ let Some(axum::Extension(CallerDevice(caller_id))) = caller else {
+ return StatusCode::UNAUTHORIZED.into_response();
+ };
+ let devices = devices.lock().await;
+ Json(own_device_rows(&devices, &caller_id)).into_response()
}
#[derive(Deserialize)]
@@ -4921,7 +4960,7 @@ fn remove_own_device(
}
async fn handle_disconnect(
- AxumState(state): AxumState<RemoteState>,
+ AxumState(DeviceRegistry(devices)): AxumState<DeviceRegistry>,
caller: Option<axum::Extension<CallerDevice>>,
Json(body): Json<DisconnectRequest>,
) -> StatusCode {
@@ -4931,7 +4970,7 @@ async fn handle_disconnect(
let Some(axum::Extension(CallerDevice(caller_id))) = caller else {
return StatusCode::UNAUTHORIZED;
};
- let mut devices = state.connected_devices.lock().await;
+ let mut devices = devices.lock().await;
remove_own_device(&mut devices, &caller_id, &body.id)
}
@@ -5155,6 +5194,76 @@ fn kill_tunnel_child(mut child: std::process::Child) {
println!("[Tunnel] Stopped (PID {})", pid);
}
+/// Spawn the tunnel and hand it to the shared state IN THE SAME STEP.
+///
+/// The child used to be held in a local variable for the whole of `start_tunnel`
+/// — the 15 s wait for the public URL plus the ~12 s edge-readiness probe. For
+/// those ~27 seconds on EVERY start the process was running and reachable from
+/// nothing: `stop_tunnel` found an empty slot, `Drop` found an empty slot, and a
+/// quit in that window left a live `*.trycloudflare.com` address pointing at
+/// this machine with the app's own indicator reading OFF. That is the same
+/// finding the `Child` was introduced for, just narrowed to a window.
+///
+/// So the slot is filled first and the outcome decided afterwards: from here on
+/// every failure path goes through `kill_registered_tunnel`, which takes the
+/// child back out of the slot instead of dropping a forgotten handle.
+///
+/// `stderr` is taken before the child leaves this function — it is the only
+/// thing the caller still needs, and after the handover the `Child` belongs to
+/// the shared state.
+fn spawn_and_register_tunnel(
+ cmd: std::process::Command,
+ remote: &std::sync::Mutex<RemoteServer>,
+) -> Result<(u32, std::process::ChildStderr), String> {
+ let mut child = crate::process_util::spawn_piped(cmd).map_err(|e| {
+ error!(error = %e, "cloudflared tunnel spawn failed");
+ format!("Failed to start cloudflared: {}", os_error::english(&e))
+ })?;
+ let pid = child.id();
+ // The tunnel is the one child whose survival is a security event and not
+ // just a leak: it publishes this machine on the internet. On Windows this
+ // puts it in the app's kill-on-close job object, so the OS takes it down
+ // even when nothing in this process gets to run a shutdown path.
+ crate::commands::process::tie_child_to_app_lifetime(pid);
+ let stderr = match child.stderr.take() {
+ Some(s) => s,
+ None => {
+ kill_tunnel_child(child);
+ return Err("cloudflared had no stderr handle".into());
+ }
+ };
+ // Anything already in the slot is killed rather than dropped — dropping a
+ // `Child` does not kill it, it just forgets it, which is how the leak this
+ // whole area fixes started.
+ let displaced = {
+ let mut guard = remote.lock().map_err(|e| e.to_string())?;
+ guard.tunnel_child.replace(child)
+ };
+ if let Some(old) = displaced {
+ kill_tunnel_child(old);
+ }
+ Ok((pid, stderr))
+}
+
+/// Take the tunnel back out of the shared slot and kill it — the failure-path
+/// counterpart of `spawn_and_register_tunnel`.
+///
+/// Only if the slot still holds THIS pid: a concurrent `start_tunnel` may have
+/// replaced it (and killed ours) already, and a failing start must never reap
+/// the tunnel that succeeded after it.
+fn kill_registered_tunnel(remote: &std::sync::Mutex<RemoteServer>, pid: u32) {
+ let child = match remote.lock() {
+ Ok(mut guard) => match guard.tunnel_child.as_ref().map(|c| c.id()) {
+ Some(held) if held == pid => guard.tunnel_child.take(),
+ _ => None,
+ },
+ Err(_) => None,
+ };
+ if let Some(child) = child {
+ kill_tunnel_child(child);
+ }
+}
+
/// Last line of defence for the public tunnel.
///
/// Tauri v2 does not reliably drop managed state on `app.exit(0)`, which is
@@ -5225,7 +5334,31 @@ fn is_stale_tunnel_process(process_name: &str, cmd: &[String], port: u16) -> boo
return false;
}
let joined = cmd.join(" ");
- joined.contains(&format!("127.0.0.1:{port}")) || joined.contains(&format!("localhost:{port}"))
+ targets_loopback_port(&joined, port)
+}
+
+/// Does this command line publish EXACTLY `port` on loopback?
+///
+/// A substring test does not answer that: `contains("127.0.0.1:1143")` is also
+/// true of `127.0.0.1:11435`, so the sweep for one port killed the tunnel of
+/// another — and this sweep runs before the bind, on processes the user may
+/// well have started for their own reasons. The whole digit run after the host
+/// has to equal the port, which rules out both a shorter prefix and a longer
+/// suffix.
+fn targets_loopback_port(text: &str, port: u16) -> bool {
+ let wanted = port.to_string();
+ for host in ["127.0.0.1:", "localhost:"] {
+ let mut rest = text;
+ while let Some(at) = rest.find(host) {
+ let tail = &rest[at + host.len()..];
+ let digits: String = tail.chars().take_while(char::is_ascii_digit).collect();
+ if digits == wanted {
+ return true;
+ }
+ rest = tail;
+ }
+ }
+ false
}
/// Kill cloudflared processes left over from a previous run that still publish
@@ -5829,26 +5962,11 @@ pub async fn start_tunnel(
// 127.0.0.1 (not "localhost") avoids a ~2 s IPv6 (::1) connect detour on
// some Windows boxes before cloudflared falls back to IPv4 (aldrich 2026-06).
cmd.args(["tunnel", "--url", &format!("http://127.0.0.1:{}", port)]);
- let mut child = crate::process_util::spawn_piped(cmd)
- .map_err(|e| {
- error!(error = %e, "cloudflared tunnel spawn failed");
- format!("Failed to start cloudflared: {}", os_error::english(&e))
- })?;
-
- let pid = child.id();
- // The tunnel is the one child whose survival is a security event and not
- // just a leak: it publishes this machine on the internet. On Windows this
- // puts it in the app's kill-on-close job object, so the OS takes it down
- // even when nothing in this process gets to run a shutdown path.
- crate::commands::process::tie_child_to_app_lifetime(pid);
+ // Registered in the shared slot BY the spawn, not once the start is judged
+ // successful — everything below this line can fail, and every one of those
+ // paths must be able to reach the process it left running.
+ let (pid, stderr) = spawn_and_register_tunnel(cmd, &state.remote)?;
info!(pid = pid, port = port, "tunnel started");
- let stderr = match child.stderr.take() {
- Some(s) => s,
- None => {
- kill_tunnel_child(child);
- return Err("cloudflared had no stderr handle".into());
- }
- };
println!("[Tunnel] cloudflared started (PID {}), tunneling localhost:{}", pid, port);
let captured_url = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
@@ -5923,7 +6041,7 @@ pub async fn start_tunnel(
// records as `tunnelActive=false` while leaving a live public tunnel
// behind is exactly the state this whole area is being fixed for.
warn!(pid = pid, "tunnel URL did not appear within 15s");
- kill_tunnel_child(child);
+ kill_registered_tunnel(&state.remote, pid);
{
let mut turl = tunnel_url_arc.lock().await;
*turl = None;
@@ -5936,17 +6054,8 @@ pub async fn start_tunnel(
));
}
- // Store the tunnel process. Held as a `Child`, so every stop path and the
- // `Drop` on `RemoteServer` can actually reap it. Anything already in the
- // slot is killed rather than dropped — dropping a `Child` does not kill it,
- // it just forgets it, which is how the leak this fixes started.
- let displaced = {
- let mut remote = state.remote.lock().map_err(|e| e.to_string())?;
- remote.tunnel_child.replace(child)
- };
- if let Some(old) = displaced {
- kill_tunnel_child(old);
- }
+ // The process is already in the slot (`spawn_and_register_tunnel`), so all
+ // that is left is publishing the URL.
// Store tunnel URL in shared state (so axum handlers see it)
{
@@ -6518,6 +6627,103 @@ mod remote_hardening_tests {
assert_eq!(devices.len(), 2, "a refused disconnect must change nothing");
}
+ // ── the disconnect/devices HANDLERS, not just their helpers ──
+ //
+ // The two tests above prove `remove_own_device`. They do NOT prove that the
+ // endpoint uses it: a gegenprüfer put the old, vulnerable body back into
+ // `handle_disconnect` and the whole suite stayed green, because nothing ran
+ // the handler. These do — the handlers take the device list as their axum
+ // sub-state precisely so they can be called here.
+
+ fn registry(devices: Vec<ConnectedDevice>) -> DeviceRegistry {
+ DeviceRegistry(Arc::new(TokioMutex::new(devices)))
+ }
+
+ fn caller(id: &str) -> Option<axum::Extension<CallerDevice>> {
+ Some(axum::Extension(CallerDevice(id.to_string())))
+ }
+
+ async fn body_json(resp: Response) -> serde_json::Value {
+ let bytes = axum::body::to_bytes(resp.into_body(), 1 << 20).await.expect("read body");
+ serde_json::from_slice(&bytes).expect("json body")
+ }
+
+ #[tokio::test]
+ async fn the_disconnect_endpoint_refuses_to_end_someone_elses_session() {
+ let now = 1_700_000_000u64;
+ let reg = registry(vec![
+ device("mine", "192.168.1.10", now),
+ device("theirs", "192.168.1.77", now),
+ ]);
+ let code = handle_disconnect(
+ AxumState(reg.clone()),
+ caller("mine"),
+ Json(DisconnectRequest { id: "theirs".into() }),
+ )
+ .await;
+ assert_eq!(code, StatusCode::FORBIDDEN, "the endpoint ended another device's session");
+ let devices = reg.0.lock().await;
+ assert_eq!(devices.len(), 2, "a refused disconnect must change nothing");
+ assert!(devices.iter().any(|d| d.id == "theirs"), "the victim's row is gone");
+ }
+
+ #[tokio::test]
+ async fn the_disconnect_endpoint_still_ends_the_callers_own_session() {
+ let now = 1_700_000_000u64;
+ let reg = registry(vec![
+ device("mine", "192.168.1.10", now),
+ device("theirs", "192.168.1.77", now),
+ ]);
+ let code = handle_disconnect(
+ AxumState(reg.clone()),
+ caller("mine"),
+ Json(DisconnectRequest { id: "mine".into() }),
+ )
+ .await;
+ assert_eq!(code, StatusCode::OK);
+ let devices = reg.0.lock().await;
+ assert_eq!(devices.len(), 1);
+ assert_eq!(devices[0].id, "theirs");
+ }
+
+ #[tokio::test]
+ async fn an_unidentified_caller_cannot_touch_the_device_list() {
+ let now = 1_700_000_000u64;
+ let reg = registry(vec![device("mine", "192.168.1.10", now)]);
+ let code = handle_disconnect(
+ AxumState(reg.clone()),
+ None,
+ Json(DisconnectRequest { id: "mine".into() }),
+ )
+ .await;
+ assert_eq!(code, StatusCode::UNAUTHORIZED);
+ assert_eq!(reg.0.lock().await.len(), 1);
+ }
+
+ #[tokio::test]
+ async fn the_devices_endpoint_shows_a_phone_only_its_own_row() {
+ // Same class as the disconnect finding: "paired" was the only rung, so
+ // every phone could read every other phone's id, address and user agent
+ // — and that id was all the disconnect endpoint asked for.
+ let now = 1_700_000_000u64;
+ let reg = registry(vec![
+ device("mine", "192.168.1.10", now),
+ device("theirs", "192.168.1.77", now),
+ ]);
+ let json = body_json(handle_devices(AxumState(reg), caller("mine")).await).await;
+ let rows = json.as_array().expect("a list of devices");
+ assert_eq!(rows.len(), 1, "the endpoint served somebody else's row: {json}");
+ assert_eq!(rows[0]["id"], "mine");
+ assert!(!json.to_string().contains("192.168.1.77"), "another device's address leaked");
+ }
+
+ #[tokio::test]
+ async fn the_devices_endpoint_refuses_an_unidentified_caller() {
+ let reg = registry(vec![device("mine", "192.168.1.10", 1_700_000_000)]);
+ let resp = handle_devices(AxumState(reg), None).await;
+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
+ }
+
// ── the pairing code ──
#[test]
@@ -6547,13 +6753,38 @@ mod remote_hardening_tests {
const REMOTE_RS: &str = include_str!("remote.rs");
- /// remote.rs up to its first test module. The assertions below quote the
- /// code they are guarding, and matching themselves would make them free.
+ /// remote.rs with EVERY `#[cfg(test)]` module cut out. The assertions below
+ /// quote the code they are guarding, and matching themselves would make
+ /// them free.
+ ///
+ /// This used to split on the first line of `jwt_refresh_tests` and keep the
+ /// head. Two test modules (`openai_bridge_tests`, `openai_bridge_live_tests`)
+ /// sit ABOVE that one, so their bodies counted as production code: a guard
+ /// that asserts a string is absent could be satisfied by a test having it,
+ /// and a guard that asserts a string is present could be satisfied by a
+ /// test quoting it. Every `#[cfg(test)]` block is removed instead, so the
+ /// result is the half that actually ships however the file is reordered.
fn production_code() -> &'static str {
- REMOTE_RS
- .split_once("#[cfg(test)]\nmod jwt_refresh_tests {")
- .map(|(head, _)| head)
- .expect("remote.rs starts its tests with jwt_refresh_tests")
+ static PROD: std::sync::OnceLock<String> = std::sync::OnceLock::new();
+ PROD.get_or_init(|| {
+ const MARKER: &str = "\n#[cfg(test)]\n";
+ let mut out = String::with_capacity(REMOTE_RS.len());
+ let mut rest = REMOTE_RS;
+ while let Some(at) = rest.find(MARKER) {
+ out.push_str(&rest[..=at]); // everything before the attribute
+ let block = &rest[at + 1..]; // starts at `#[cfg(test)]`
+ // A top-level item ends at the first `}` in column 0.
+ match block.find("\n}\n") {
+ Some(end) => rest = &block[end + 3..],
+ None => {
+ rest = "";
+ break;
+ }
+ }
+ }
+ out.push_str(rest);
+ out
+ })
}
#[test]
@@ -6564,6 +6795,27 @@ mod remote_hardening_tests {
assert!(head.len() < REMOTE_RS.len(), "the split kept the test modules");
assert!(head.contains("async fn handle_auth("), "the split dropped production code");
assert!(!head.contains("mod remote_hardening_tests"), "the split kept this module");
+ // EVERY test module, not just the first one: the modules above
+ // jwt_refresh_tests used to count as production code.
+ for m in [
+ "mod openai_bridge_tests",
+ "mod openai_bridge_live_tests",
+ "mod jwt_refresh_tests",
+ "mod proxy_gate_path_tests",
+ "mod remote_path_tests",
+ "mod mobile_decay_tests",
+ "mod mobile_environment_tests",
+ ] {
+ assert!(!head.contains(m), "the split kept {m}");
+ }
+ assert!(
+ !head.contains("#[cfg(test)]"),
+ "a test-only block survived the split",
+ );
+ // And it must not have eaten the production code that follows the
+ // first test module — build_router lives well below it.
+ assert!(head.contains("fn build_router("), "the split dropped everything after the first test module");
+ assert!(head.contains("pub async fn start_tunnel("), "the split dropped the tunnel code");
}
/// The body of a top-level `fn` in the production half, from its signature
@@ -6681,6 +6933,27 @@ mod remote_hardening_tests {
assert!(!is_stale_tunnel_process("cloudflared", &cmd("cloudflared --version"), 11435));
}
+ #[test]
+ fn a_sweep_for_one_port_does_not_kill_the_tunnel_of_another() {
+ // The port was matched as a substring, so `127.0.0.1:1143` was "found"
+ // inside `127.0.0.1:11435` — a sweep for 1143 killed the tunnel that
+ // publishes 11435, and this sweep runs before the bind on processes the
+ // user may have started themselves.
+ let cmd = |s: &str| s.split(' ').map(String::from).collect::<Vec<_>>();
+ let live = cmd("cloudflared tunnel --url http://127.0.0.1:11435");
+ assert!(!is_stale_tunnel_process("cloudflared", &live, 1143), "a prefix of the port matched");
+ assert!(!is_stale_tunnel_process("cloudflared", &live, 1), "a shorter prefix matched");
+ assert!(!is_stale_tunnel_process("cloudflared", &live, 435), "a suffix of the port matched");
+ assert!(is_stale_tunnel_process("cloudflared", &live, 11435), "the exact port stopped matching");
+ // Same rule for the spelled-out host.
+ let local = cmd("cloudflared tunnel --url http://localhost:11435");
+ assert!(!is_stale_tunnel_process("cloudflared", &local, 1143));
+ assert!(is_stale_tunnel_process("cloudflared", &local, 11435));
+ // A port that only appears as part of a longer number is not our port.
+ assert!(!targets_loopback_port("http://127.0.0.1:114350", 11435));
+ assert!(!targets_loopback_port("http://127.0.0.1:911435", 11435));
+ }
+
/// A live child that outlives the test unless something kills it, spawned
/// the way the tunnel is.
#[cfg(unix)]
@@ -6742,6 +7015,62 @@ mod remote_hardening_tests {
);
}
+ #[test]
+ #[cfg(unix)]
+ fn the_tunnel_is_in_the_shared_slot_from_the_moment_it_is_spawned() {
+ // The finding the `Child` was introduced for, narrowed to a window: the
+ // process was held in a local variable until the start was judged
+ // successful — 15 s waiting for the public URL plus ~12 s probing the
+ // edge. For those ~27 seconds on EVERY start, `stop_tunnel` and `Drop`
+ // both looked at an empty slot while a public *.trycloudflare.com
+ // address was already live.
+ let remote = std::sync::Mutex::new(RemoteServer::new());
+ let mut cmd = std::process::Command::new("sleep");
+ cmd.arg("30");
+ let (pid, _stderr) = spawn_and_register_tunnel(cmd, &remote).expect("spawn a stand-in tunnel");
+ assert!(alive(pid), "the stand-in tunnel did not start");
+ assert_eq!(
+ remote.lock().unwrap().tunnel_pid(),
+ Some(pid),
+ "the spawned tunnel is not reachable from the state every stop path reads",
+ );
+
+ // ...which is exactly what makes the failure paths able to close it.
+ kill_registered_tunnel(&remote, pid);
+ assert!(remote.lock().unwrap().tunnel_pid().is_none(), "the slot still holds a dead tunnel");
+ assert!(
+ dies_within(pid, std::time::Duration::from_secs(5)),
+ "a failed start left the tunnel running",
+ );
+ }
+
+ #[test]
+ #[cfg(unix)]
+ fn a_failed_start_never_reaps_the_tunnel_that_replaced_it() {
+ // Two starts race: the second replaces (and kills) the first, then the
+ // first one's timeout fires. It must not take the live tunnel down.
+ let remote = std::sync::Mutex::new(RemoteServer::new());
+ let mut first = std::process::Command::new("sleep");
+ first.arg("30");
+ let (first_pid, _e1) = spawn_and_register_tunnel(first, &remote).expect("spawn first");
+ let mut second = std::process::Command::new("sleep");
+ second.arg("30");
+ let (second_pid, _e2) = spawn_and_register_tunnel(second, &remote).expect("spawn second");
+ assert_ne!(first_pid, second_pid);
+ assert!(dies_within(first_pid, std::time::Duration::from_secs(5)), "the displaced tunnel survived");
+
+ kill_registered_tunnel(&remote, first_pid);
+ assert_eq!(
+ remote.lock().unwrap().tunnel_pid(),
+ Some(second_pid),
+ "the stale failure path evicted the live tunnel",
+ );
+ assert!(alive(second_pid), "the stale failure path killed the live tunnel");
+
+ kill_registered_tunnel(&remote, second_pid);
+ assert!(dies_within(second_pid, std::time::Duration::from_secs(5)));
+ }
+
#[test]
#[cfg(unix)]
fn a_stopped_tunnel_is_reaped_and_not_left_as_a_zombie() {
@@ -6756,6 +7085,36 @@ mod remote_hardening_tests {
);
}
+ #[test]
+ #[cfg(unix)]
+ fn stopping_the_tunnel_takes_its_children_with_it() {
+ // `process_util::kill_tree` has two callers, and they do not spawn the
+ // same way: video_cancel uses a plain `Command::spawn` (the child is in
+ // OUR process group), this one uses `spawn_piped` (the child is its own
+ // group leader). The walk is by parent link, so the difference must not
+ // matter — asserted here rather than assumed, because the comment on
+ // kill_tree used to claim video_cancel was the only caller.
+ let mut cmd = std::process::Command::new("sh");
+ cmd.arg("-c").arg("sleep 30 & sleep 30");
+ let child = crate::process_util::spawn_piped(cmd).expect("spawn a tunnel stand-in");
+ let pid = child.id();
+ std::thread::sleep(std::time::Duration::from_millis(400));
+
+ let mut sys = sysinfo::System::new();
+ sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
+ let kids = crate::commands::shell::descendants(pid, &sys);
+ assert!(!kids.is_empty(), "the stand-in spawned nothing — test setup is wrong");
+
+ kill_tunnel_child(child);
+
+ for p in kids.iter().copied().chain(std::iter::once(pid)) {
+ assert!(
+ dies_within(p, std::time::Duration::from_secs(5)),
+ "{p} survived the tunnel stop",
+ );
+ }
+ }
+
#[test]
fn dropping_a_server_without_a_tunnel_is_a_no_op() {
drop(RemoteServer::new());
diff --git a/src-tauri/src/commands/shell.rs b/src-tauri/src/commands/shell.rs
index cfeb77e9..3a8bc744 100644
--- a/src-tauri/src/commands/shell.rs
+++ b/src-tauri/src/commands/shell.rs
@@ -373,11 +373,20 @@ mod ipc_surface_tests {
}
assert!(!spawn_entries.is_empty(), "no shell:allow-spawn entry found");
+ // Every one of the NINETEEN entries the hardening commit removed, and
+ // not a subset: the list had 15, so `bunx`, `bunx.cmd`, `pnpm.cmd` and
+ // `yarn.cmd` could have been put back without a single test noticing.
+ // `bunx` is the one that matters most — it is npx's exact equivalent,
+ // it fetches a package off the network and runs it, and it was in the
+ // allow-list with `"args": true`.
+ //
// Anything that runs code handed to it on the command line, or that
// runs whatever a package.json / image says.
- const BANNED: [&str; 15] = [
- "node", "node.cmd", "deno", "deno.cmd", "bun", "bun.cmd", "python", "python3",
- "py", "docker", "npm", "npm.cmd", "pnpm", "yarn", "uv",
+ const BANNED: [&str; 19] = [
+ "node", "node.cmd", "deno", "deno.cmd",
+ "bun", "bun.cmd", "bunx", "bunx.cmd",
+ "python", "python3", "py", "docker",
+ "npm", "npm.cmd", "pnpm", "pnpm.cmd", "yarn", "yarn.cmd", "uv",
];
for entry in &spawn_entries {
let name = entry["name"].as_str().unwrap_or_default().to_lowercase();
@@ -484,9 +493,22 @@ mod tests {
let cwd = workspace_cwd(Some(id));
assert!(cwd.starts_with(&root), "id {id:?} escaped to {cwd:?}");
assert_ne!(cwd, root, "id {id:?} landed on the workspace root itself");
+ // Only the SLUG, never the whole path: a machine whose home is
+ // /Users/max.mustermann has a dot in every path under it, and this
+ // assertion used to fail there for a reason that has nothing to do
+ // with the chat id.
+ //
+ // The last COMPONENT, not `file_name()`: `file_name()` answers None
+ // for a path ending in `..`, which is precisely the id this is
+ // guarding against — the check would pass by not looking.
+ let slug = cwd
+ .components()
+ .next_back()
+ .map(|c| c.as_os_str().to_string_lossy().to_string())
+ .unwrap_or_default();
assert!(
- !cwd.to_string_lossy().contains('.'),
- "id {id:?} kept a dot: {cwd:?}",
+ !slug.contains('.'),
+ "id {id:?} kept a dot in its folder name: {slug:?} (from {cwd:?})",
);
}
// Ordinary ids keep their own folder.
diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs
index e2803520..c903c2a8 100644
--- a/src-tauri/src/commands/system.rs
+++ b/src-tauri/src/commands/system.rs
@@ -219,6 +219,20 @@ fn capture_screen_to(_tmp: &std::path::Path) -> Result<(), String> {
Err("Screenshot not implemented for this platform yet".to_string())
}
+/// The native folder dialog — and the ONLY way a folder joins the workspace
+/// allowlist (`filesystem::remember_picked_root`).
+///
+/// That is the whole point of routing it through here: the jail root for every
+/// agent/remote file op used to be a string the WebView sent, so a script
+/// injected into the renderer could name `/` and read the disk through
+/// `fs_read`. A renderer cannot open this dialog or click in it, so "folders a
+/// human chose here" is a set it cannot extend.
+///
+/// Recording is best-effort on purpose: this dialog also picks folders that are
+/// not workspaces at all (the GGUF download path, for instance). A folder that
+/// may not be a jail root — `$HOME`, `/`, a credential directory — is simply
+/// not recorded, and the picker still returns it for those other uses; only
+/// `check_workspace_root` cares, and it refuses with the reason.
#[tauri::command]
pub async fn pick_folder(default_path: Option<String>) -> Result<Option<String>, String> {
let mut dialog = rfd::AsyncFileDialog::new();
@@ -226,7 +240,11 @@ pub async fn pick_folder(default_path: Option<String>) -> Result<Option<String>,
dialog = dialog.set_directory(p);
}
let result = dialog.pick_folder().await;
- Ok(result.map(|f| f.path().to_string_lossy().to_string()))
+ let picked = result.map(|f| f.path().to_path_buf());
+ if let Some(ref p) = picked {
+ let _ = crate::commands::filesystem::remember_picked_root(p);
+ }
+ Ok(picked.map(|p| p.to_string_lossy().to_string()))
}
/// Exit the app — used by the auto-updater to let the NSIS installer swap
diff --git a/src-tauri/src/commands/whisper.rs b/src-tauri/src/commands/whisper.rs
index 492060eb..87fe4454 100644
--- a/src-tauri/src/commands/whisper.rs
+++ b/src-tauri/src/commands/whisper.rs
@@ -372,15 +372,23 @@ fn transcribe_blocking(
else if content_type.contains("mp4") || content_type.contains("m4a") { ".m4a" }
else { ".webm" };
- // Write to temp file
- let tmp_dir = std::env::temp_dir();
- let tmp_file = tmp_dir.join(format!("whisper-{}{}", std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_millis())
- .unwrap_or(0), ext));
-
- std::fs::write(&tmp_file, &audio_bytes)
- .map_err(|e| format!("Write temp file: {}", os_error::english(&e)))?;
+ // The take goes to a private temp file — a 0700 directory, a 0600 file
+ // created with `create_new`, and a name nothing on the machine can compute.
+ //
+ // It used to be `<shared temp>/whisper-<millis>.<ext>`, written with
+ // fs::write. That is a recording of the user's voice in a world-readable
+ // directory under a guessable name: every local account could read the take,
+ // and a process that guessed the name could pre-place it or swap it between
+ // the write and the moment whisper_server.py opens it — the transcript of
+ // whatever it swapped in then lands in the user's chat. The identical fix
+ // was made for the agent's script and left un-made here; both now share
+ // `private_tmp::write_private_temp`.
+ //
+ // `_audio_dir` is never read, only held: dropping it removes the directory
+ // and the take with it, which is what the explicit remove_file below used to
+ // do — and it now also covers the early returns that used to leak the file.
+ let (_audio_dir, tmp_file) =
+ crate::private_tmp::write_private_temp("lu-whisper-take-", &format!("take{}", ext), &audio_bytes)?;
let audio_path = tmp_file.to_string_lossy().replace('\\', "/");
println!("[Whisper] Transcribing: {} ({:.1} KB)", audio_path, audio_bytes.len() as f64 / 1024.0);
@@ -418,8 +426,9 @@ fn transcribe_blocking(
}
}
- // Clean up temp file, after the retry, which reads the same file.
- let _ = std::fs::remove_file(&tmp_file);
+ // Clean up temp file, after the retry, which reads the same file. Dropping
+ // the directory handle takes the take with it.
+ drop(_audio_dir);
match result {
Ok(response) => {
@@ -843,8 +852,55 @@ mod healing_is_wired_in {
let s = source();
let send = s.find("let mut result = send_to_whisper").expect("the send is gone");
let retry = s.find("if whisper_is_gone(state, why)").expect("the retry is gone");
- let cleanup = s.find("let _ = std::fs::remove_file(&tmp_file);").expect("the cleanup is gone");
+ let cleanup = s.find("drop(_audio_dir);").expect("the cleanup is gone");
assert!(send < retry, "the retry must come after the first send");
assert!(retry < cleanup, "the audio was deleted before the retry could read it");
}
+
+ /// The take is a recording of the user's voice. It used to be written with
+ /// `fs::write` to `<shared temp>/whisper-<millis>.<ext>`: world-readable,
+ /// and under a name any local process can compute — so it could be
+ /// pre-placed or swapped between the write and the read, and whatever was
+ /// swapped in got transcribed into the user's chat. The fix already existed
+ /// for the agent's script; this half kept its own unfixed copy.
+ #[test]
+ fn the_take_is_written_through_the_shared_private_temp_helper() {
+ let s = source();
+ assert!(
+ s.contains("crate::private_tmp::write_private_temp(\"lu-whisper-take-\""),
+ "the take is not written through the shared private-temp helper any more",
+ );
+ // The old shape, in either of its two halves.
+ assert!(
+ !s.contains("let tmp_dir = std::env::temp_dir();"),
+ "the take is back in the shared temp directory",
+ );
+ assert!(
+ !s.contains("std::fs::write(&tmp_file, &audio_bytes)"),
+ "the take is written with a plain fs::write again (umask permissions)",
+ );
+ }
+
+ /// The property itself, not the call site: a take must not be readable by
+ /// another account on the machine.
+ #[cfg(unix)]
+ #[test]
+ fn a_take_is_private_to_this_user() {
+ use std::os::unix::fs::PermissionsExt;
+ let (dir, path) =
+ crate::private_tmp::write_private_temp("lu-whisper-take-", "take.webm", b"audio")
+ .expect("write a take");
+ let dmode = std::fs::metadata(dir.path()).unwrap().permissions().mode() & 0o777;
+ assert_eq!(dmode, 0o700, "the take's directory is {dmode:o}, not 0700");
+ let fmode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
+ assert_eq!(fmode & 0o077, 0, "the take is group/world readable: {fmode:o}");
+ let name = dir.path().file_name().unwrap().to_string_lossy().to_string();
+ let suffix = name.trim_start_matches("lu-whisper-take-");
+ assert!(
+ !suffix.chars().all(|c| c.is_ascii_digit()),
+ "the directory name is a plain timestamp again: {name}",
+ );
+ drop(dir);
+ assert!(!path.exists(), "the take outlived its handle");
+ }
}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 319bbd85..775e6e3a 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -6,6 +6,7 @@ mod crash_report;
mod install_state;
mod os_error;
mod os_paths;
+mod private_tmp;
mod process_util;
mod python;
mod state;
diff --git a/src-tauri/src/private_tmp.rs b/src-tauri/src/private_tmp.rs
new file mode 100644
index 00000000..c6b86bcf
--- /dev/null
+++ b/src-tauri/src/private_tmp.rs
@@ -0,0 +1,113 @@
+//! One private temp file, done once.
+//!
+//! Two places in this app hand a file to a child process it has to read back:
+//! the agent's Python script (`commands::agent`) and a dictation take's audio
+//! (`commands::whisper`). Both started the same way — `<shared temp>/<name>-<
+//! millisecond timestamp>.<ext>`, written with `fs::write` — and both had the
+//! same two problems.
+//!
+//! * The system temp directory is world-readable (0777+t on Unix, and every
+//! local account can list it). The agent's script carries whatever the user
+//! or the model put in it; a dictation take is a recording of the user's
+//! voice. Neither is something every account on the machine gets to read.
+//! * A millisecond timestamp is not a name, it is a guess anyone can make. A
+//! local process that guesses it can pre-place the path (so the write lands
+//! in a file it owns) or swap it between the write and the read — the second
+//! one is the classic temp race, and here the swapped-in content is executed
+//! by an interpreter or transcribed and put in the user's chat.
+//!
+//! The fix was made once for the script and left un-made for the audio. It
+//! lives here now so there is nothing left to make twice: a directory created
+//! by `mkdir(0700)` — the mode goes to the syscall, not to a chmod afterwards,
+//! so the directory is never briefly readable — holding a file created with
+//! `create_new` (a pre-placed name is an error, never a target) and 0600. The
+//! returned `TempDir` owns the lifetime: dropping it removes the directory and
+//! its contents, including on every early return of the caller.
+
+use crate::os_error;
+use std::path::PathBuf;
+
+/// Write `bytes` to `file_name` inside a fresh 0700 temp directory.
+///
+/// The caller must keep the returned `TempDir` alive for as long as the file is
+/// needed — dropping it deletes both.
+pub fn write_private_temp(
+ dir_prefix: &str,
+ file_name: &str,
+ bytes: &[u8],
+) -> Result<(tempfile::TempDir, PathBuf), String> {
+ use std::io::Write;
+ let mut builder = tempfile::Builder::new();
+ builder.prefix(dir_prefix);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ builder.permissions(std::fs::Permissions::from_mode(0o700));
+ }
+ let dir = builder
+ .tempdir()
+ .map_err(|e| format!("Create temp dir: {}", os_error::english(&e)))?;
+ let path = dir.path().join(file_name);
+ let mut opts = std::fs::OpenOptions::new();
+ opts.write(true).create_new(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ opts.mode(0o600);
+ }
+ let mut file = opts
+ .open(&path)
+ .map_err(|e| format!("Write temp file: {}", os_error::english(&e)))?;
+ file.write_all(bytes)
+ .map_err(|e| format!("Write temp file: {}", os_error::english(&e)))?;
+ Ok((dir, path))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_file_lands_in_a_private_directory_under_an_unguessable_name() {
+ let (dir_a, path_a) = write_private_temp("lu-test-", "payload.bin", b"a").expect("write");
+ let (dir_b, _path_b) = write_private_temp("lu-test-", "payload.bin", b"b").expect("write");
+ assert_eq!(std::fs::read(&path_a).unwrap(), b"a");
+ assert_ne!(dir_a.path(), dir_b.path(), "two calls shared a directory");
+ let name = dir_a.path().file_name().unwrap().to_string_lossy().to_string();
+ let suffix = name.trim_start_matches("lu-test-");
+ assert!(suffix.len() >= 6, "name is too short to be unguessable: {name}");
+ assert!(
+ !suffix.chars().all(|c| c.is_ascii_digit()),
+ "the name is a plain number again: {name}",
+ );
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn nothing_outside_this_user_can_read_it() {
+ use std::os::unix::fs::PermissionsExt;
+ let (dir, path) = write_private_temp("lu-test-", "secret.wav", b"voice").expect("write");
+ let dmode = std::fs::metadata(dir.path()).unwrap().permissions().mode() & 0o777;
+ assert_eq!(dmode, 0o700, "temp dir is {dmode:o}, not 0700");
+ let fmode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
+ assert_eq!(fmode & 0o077, 0, "file is group/world accessible: {fmode:o}");
+ }
+
+ #[test]
+ fn dropping_the_handle_removes_the_directory() {
+ let (dir, path) = write_private_temp("lu-test-", "x.txt", b"x").expect("write");
+ let dir_path = dir.path().to_path_buf();
+ drop(dir);
+ assert!(!path.exists());
+ assert!(!dir_path.exists());
+ }
+
+ #[test]
+ fn an_existing_name_is_an_error_and_not_a_target() {
+ let (dir, path) = write_private_temp("lu-test-", "once.txt", b"first").expect("write");
+ let mut opts = std::fs::OpenOptions::new();
+ opts.write(true).create_new(true);
+ assert!(opts.open(&path).is_err(), "create_new accepted an existing path");
+ drop(dir);
+ }
+}
diff --git a/src-tauri/src/process_util.rs b/src-tauri/src/process_util.rs
index 334bb310..f88c3627 100644
--- a/src-tauri/src/process_util.rs
+++ b/src-tauri/src/process_util.rs
@@ -82,19 +82,34 @@ fn tree_snapshot(root: u32) -> Vec<(u32, u64)> {
/// Recursive process-tree kill: SIGTERM the whole tree now, SIGKILL whatever
/// is left after a grace. Windows delegates the walk to `taskkill /T /F`.
///
-/// The Unix branch used to signal the process GROUP (`kill -- -PGID`). Only
-/// `spawn_piped` puts a child in its own group, and its one caller here
-/// (`video_cancel` → the mlx_video Python job) spawns through a plain
-/// `Command::spawn`, so `-PID` addressed a group that never existed: the kill
-/// went nowhere and the generation kept running on the GPU. The tree is
-/// therefore walked explicitly, and it MUST be walked before the root dies —
-/// afterwards its children are reparented to init and the parent links that
-/// identify them are gone.
+/// The Unix branch used to signal the process GROUP (`kill -- -PGID`). That
+/// only reaches a child that was made a group leader at spawn, and it is not
+/// what either caller here does:
+///
+/// * `video::video_cancel` (the mlx_video Python job) spawns through a plain
+/// `Command::spawn`, so the child is in OUR group and `-PID` addressed a
+/// group that never existed — the kill went nowhere and the generation kept
+/// running on the GPU. This is the case the explicit walk was written for.
+/// * `remote::kill_tunnel_child` (the cloudflared quick tunnel) spawns through
+/// `spawn_piped`, so that child IS its own group leader and the old group
+/// kill would have worked for it. The walk works for it too: it follows the
+/// parent links, which exist either way, and it never signals a pid that is
+/// not in the snapshot — so the wider process group is not a hazard.
+///
+/// What BOTH callers have to satisfy is the reaping contract: the tree MUST be
+/// walked before the root dies (afterwards its children are reparented to init
+/// and the parent links that identify them are gone), and the caller must not
+/// have reaped the child itself — the `waitpid` at the end of the detached
+/// thread is what keeps the pid reserved until the escalation has fired, and it
+/// is also what keeps the process from becoming a permanent zombie. Both
+/// callers hand over an unreaped `Child` and drop it afterwards without
+/// waiting, which is exactly right.
///
/// Nothing here blocks the caller: `video_cancel` holds the `video_process`
/// mutex across this call and the UI polls that same mutex, so the old
-/// 800 ms sleep froze the window for the whole grace. The grace, the escalation
-/// and the final reap run on a detached thread instead.
+/// 800 ms sleep froze the window for the whole grace. The tunnel path has the
+/// same shape on quit. The grace, the escalation and the final reap run on a
+/// detached thread instead.
pub fn kill_tree(child: &mut Child) -> std::io::Result<()> {
let pid = child.id();
#[cfg(windows)]
@@ -246,9 +261,12 @@ mod kill_tree_tests {
}
}
- /// The only caller (`video_cancel`) spawns with a plain `Command::spawn`,
- /// so the child is NOT a process-group leader — which is exactly why the
- /// old `kill(-pid)` signalled nothing and left the tree running.
+ /// One of the two callers (`video_cancel`) spawns with a plain
+ /// `Command::spawn`, so the child is NOT a process-group leader — which is
+ /// exactly why the old `kill(-pid)` signalled nothing and left the tree
+ /// running. (The other, `remote::kill_tunnel_child`, goes through
+ /// `spawn_piped` and IS a group leader; the parent-link walk covers both,
+ /// and the group-leader case is exercised in remote.rs's own tunnel tests.)
#[test]
fn a_child_without_a_process_group_still_loses_its_whole_tree() {
let mut child = Command::new("sh")