diff --git a/docs/features/remote-workspaces.md b/docs/features/remote-workspaces.md index b720db6e00..ad4be47869 100644 --- a/docs/features/remote-workspaces.md +++ b/docs/features/remote-workspaces.md @@ -98,7 +98,10 @@ the container. OpenBitFun does not silently translate host paths to container paths. File transfer uses binary stdin/stdout streams. Uploads write to a same-directory temporary file and rename atomically after success; cancellation leaves the previous destination intact. Ordinary SSH workspaces continue to use -SFTP. +SFTP for file transfers. Recursive directory deletion runs one command on the +effective SSH, Docker or WSL target, rather than enumerating and deleting each +child across the connection. It requires target-side shell execution and removes +symbolic links without following their targets. Text command output is decoded as one UTF-8 byte stream, so a multibyte character split across SSH or Docker chunks is preserved. File bytes are never diff --git a/src/apps/desktop/src/api/ssh_api.rs b/src/apps/desktop/src/api/ssh_api.rs index 6cf11d3e9b..ce1a38a3e4 100644 --- a/src/apps/desktop/src/api/ssh_api.rs +++ b/src/apps/desktop/src/api/ssh_api.rs @@ -359,18 +359,18 @@ pub async fn remote_remove( if recursive { remote_fs.remove_dir_all(&connection_id, &path).await } else { - // Check if it's a directory by trying to read it - let entries = remote_fs.read_dir(&connection_id, &path).await; - match entries { - Ok(_) => { - // It's a directory, but non-recursive remove of non-empty dir - // Try to remove it anyway (will fail if not empty) - remote_fs.remove_dir_all(&connection_id, &path).await - } - Err(_) => { - // Not a directory or empty, remove as file - remote_fs.remove_file(&connection_id, &path).await - } + // A non-recursive request must never delete directory contents. Use + // no-follow metadata so directory links are unlinked as files, and + // preserve metadata errors instead of guessing the path's type. + let entry = remote_fs + .symlink_stat(&connection_id, &path) + .await + .map_err(|error| error.to_string())? + .ok_or_else(|| format!("Remote path does not exist: {path}"))?; + if entry.is_dir && !entry.is_symlink { + remote_fs.remove_dir(&connection_id, &path).await + } else { + remote_fs.remove_file(&connection_id, &path).await } } .map_err(|e| e.to_string()) diff --git a/src/crates/services/services-integrations/AGENTS.md b/src/crates/services/services-integrations/AGENTS.md index c6b9af915e..7a227b1373 100644 --- a/src/crates/services/services-integrations/AGENTS.md +++ b/src/crates/services/services-integrations/AGENTS.md @@ -187,6 +187,12 @@ and `OPENBITFUN_TEST_SFTP_SERVER` set. This runs real OpenSSH SFTP over loopback and the Docker command adapter against a local POSIX shell fixture; the latter does not establish real Docker-daemon or Windows WSL coverage. +For recursive remote directory deletion, use the same package/features with +`--lib recursive_directory_delete`. This covers one SSH exec with no per-file +SFTP requests, literal filenames, symlink preservation, invalid targets and +command rejection, plus the Docker command adapter against a local POSIX shell. +It does not establish real Docker, Windows WSL, Peer Device or mobile coverage. + For the remote Flashgrep distribution gate and retained protocol helpers, use: ```bash diff --git a/src/crates/services/services-integrations/src/remote_ssh/manager.rs b/src/crates/services/services-integrations/src/remote_ssh/manager.rs index 9b2c53fbeb..bcc99132d1 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/manager.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/manager.rs @@ -6116,6 +6116,42 @@ impl SSHConnectionManager { .await } + /// Recursive deletion is a single operation on the effective SSH, Docker, + /// or WSL target. Never enumerate children across the transport boundary. + pub async fn remove_workspace_directory_all( + &self, + connection_id: &str, + path: &str, + ) -> anyhow::Result<()> { + // Expand only the home prefix. The general SFTP path resolver trims + // whitespace, which could select a different directory for deletion. + let path = if path == "~" || path.starts_with("~/") { + let home = self.resolve_sftp_path(connection_id, "~").await?; + format!("{}{}", home.trim_end_matches('/'), &path[1..]) + } else { + path.to_owned() + }; + let command = super::shell::remove_directory_command(&path)?; + let (_, stderr, status) = self + .execute_workspace_bytes(connection_id, &command) + .await + .map_err(|error| anyhow!("Failed to execute remote directory deletion: {error}"))?; + if status == -1 { + anyhow::bail!( + "Remote directory deletion returned no exit status; the host may have rejected command execution or disconnected" + ); + } + if status != 0 { + anyhow::bail!( + "Failed to remove remote directory '{}': exit_status={} {}", + path, + status, + container_stderr_detail(&stderr) + ); + } + Ok(()) + } + pub async fn container_remove( &self, connection_id: &str, @@ -8242,6 +8278,40 @@ mod tests { (manager, provider) } + #[cfg(unix)] + #[tokio::test] + async fn workspace_recursive_directory_delete_shell() { + use openbitfun_runtime_ports::WorkspaceFileSystem; + use std::os::unix::fs::symlink; + let temp = tempfile::tempdir().unwrap(); + let (_manager, provider) = shell_workspace_provider_fixture(temp.path()).await; + let target = temp.path().join("delete 'quoted' $(printf injected) "); + let keep = temp.path().join("keep"); + std::fs::write(&keep, b"keep").unwrap(); + std::fs::create_dir_all(target.join("nested")).unwrap(); + for file in 0..100 { + std::fs::write(target.join("nested").join(file.to_string()), b"delete").unwrap(); + } + symlink(&keep, target.join("outside-link")).unwrap(); + assert!(provider + .remove_dir(target.to_str().unwrap(), false) + .await + .is_err()); + assert!(target.join("nested/0").exists()); + provider + .remove_dir(&format!("{}/", target.display()), true) + .await + .unwrap(); + assert!(!target.exists()); + assert_eq!(std::fs::read(&keep).unwrap(), b"keep"); + let error = provider + .remove_dir(keep.to_str().unwrap(), true) + .await + .unwrap_err(); + assert!(error.to_string().contains("not a directory")); + assert_eq!(std::fs::read(&keep).unwrap(), b"keep"); + } + #[cfg(unix)] #[tokio::test] async fn workspace_directory_symlink_browsing_shell() { diff --git a/src/crates/services/services-integrations/src/remote_ssh/manager/tests/workspace_sftp.rs b/src/crates/services/services-integrations/src/remote_ssh/manager/tests/workspace_sftp.rs index ad69759261..8a7c8e9d21 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/manager/tests/workspace_sftp.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/manager/tests/workspace_sftp.rs @@ -15,6 +15,10 @@ struct State { closed: AtomicUsize, live: AtomicUsize, channels: AtomicUsize, + #[cfg(unix)] + execs: AtomicUsize, + #[cfg(unix)] + reject_exec: AtomicBool, pause_open: AtomicBool, pause_read: AtomicBool, pause_dir: AtomicBool, @@ -302,6 +306,37 @@ impl russh::server::Handler for SshServer { self.channels.insert(channel.id(), channel); Ok(true) } + #[cfg(unix)] + async fn exec_request( + &mut self, + id: russh::ChannelId, + command: &[u8], + session: &mut russh::server::Session, + ) -> Result<(), Self::Error> { + self.state.execs.fetch_add(1, Ordering::SeqCst); + if self.state.reject_exec.load(Ordering::SeqCst) { + session.channel_failure(id); + session.close(id); + self.channels.remove(&id); + return Ok(()); + } + session.channel_success(id); + let output = process_manager::create_tokio_command("/bin/sh") + .arg("-c") + .arg(std::str::from_utf8(command).unwrap()) + .stdin(Stdio::null()) + .kill_on_drop(true) + .output() + .await + .unwrap(); + session.data(id, russh::CryptoVec::from_slice(&output.stdout)); + session.extended_data(id, 1, russh::CryptoVec::from_slice(&output.stderr)); + session.exit_status_request(id, output.status.code().unwrap_or(1) as u32); + session.eof(id); + session.close(id); + self.channels.remove(&id); + Ok(()) + } async fn subsystem_request( &mut self, id: russh::ChannelId, @@ -385,6 +420,105 @@ impl russh::server::Handler for SshServer { } } +#[cfg(unix)] +#[tokio::test] +async fn recursive_directory_delete_uses_one_exec_and_no_sftp() { + use std::os::unix::fs::symlink; + let f = Fixture::new().await; + let service = crate::remote_ssh::RemoteFileService::new(Arc::new(tokio::sync::RwLock::new( + Some(f.manager.as_ref().clone()), + ))); + let root = f._dir.path(); + let target = root.join("delete 'quoted'; $(printf injected) `printf injected` \\ \n "); + let outside = root.join("keep"); + std::fs::create_dir(&outside).unwrap(); + std::fs::write(outside.join("sentinel"), b"keep").unwrap(); + for directory in 0..10 { + let nested = target.join(format!("nested-{directory}")); + std::fs::create_dir_all(&nested).unwrap(); + for file in 0..50 { + std::fs::write(nested.join(format!("file-{file}")), b"delete").unwrap(); + } + } + std::fs::write(target.join(".hidden"), b"delete").unwrap(); + symlink(&outside, target.join("outside-link")).unwrap(); + symlink("missing", target.join("dangling-link")).unwrap(); + service + .remove_dir_all("sftp-test", &format!("{}///", target.display())) + .await + .unwrap(); + assert!(!target.exists()); + assert_eq!(std::fs::read(outside.join("sentinel")).unwrap(), b"keep"); + assert_eq!(f.state.execs.load(Ordering::SeqCst), 1); + assert_eq!(f.state.channels.load(Ordering::SeqCst), 0); + + for (name, destination) in [ + ("directory-link", outside.clone()), + ("broken-link", root.join("missing")), + ] { + let link = root.join(name); + symlink(destination, &link).unwrap(); + service + .remove_dir_all("sftp-test", &format!("{}/", link.display())) + .await + .unwrap(); + assert!(std::fs::symlink_metadata(&link).is_err()); + assert_eq!(std::fs::read(outside.join("sentinel")).unwrap(), b"keep"); + } + let error = service + .remove_dir_all("sftp-test", outside.join("sentinel").to_str().unwrap()) + .await + .unwrap_err(); + assert!(error.to_string().contains("not a directory")); + assert_eq!(std::fs::read(outside.join("sentinel")).unwrap(), b"keep"); + let error = service + .remove_dir_all("sftp-test", root.join("missing").to_str().unwrap()) + .await + .unwrap_err(); + assert!(error.to_string().contains("does not exist")); +} + +#[cfg(unix)] +#[tokio::test] +async fn recursive_directory_delete_rejects_unsafe_paths_and_exec_failure() { + let f = Fixture::new().await; + let service = crate::remote_ssh::RemoteFileService::new(Arc::new(tokio::sync::RwLock::new( + Some(f.manager.as_ref().clone()), + ))); + for path in [ + "", + "/", + "///", + "relative", + "/tmp/.", + "/tmp/../", + "/tmp/invalid\0name", + ] { + assert!( + service.remove_dir_all("sftp-test", path).await.is_err(), + "{path:?}" + ); + } + assert_eq!(f.state.execs.load(Ordering::SeqCst), 0); + + let target = f._dir.path().join("must stay"); + std::fs::create_dir(&target).unwrap(); + std::fs::write(target.join("sentinel"), b"keep").unwrap(); + f.state.reject_exec.store(true, Ordering::SeqCst); + let error = service + .remove_dir_all("sftp-test", target.to_str().unwrap()) + .await + .unwrap_err(); + assert!(error.to_string().contains("no exit status"), "{error}"); + assert_eq!(std::fs::read(target.join("sentinel")).unwrap(), b"keep"); + assert_eq!(f.state.execs.load(Ordering::SeqCst), 1); + assert_eq!( + f.state.channels.load(Ordering::SeqCst), + 0, + "must not fall back to per-file SFTP deletion" + ); +} + struct Fixture { manager: Arc, state: Arc, diff --git a/src/crates/services/services-integrations/src/remote_ssh/remote_fs.rs b/src/crates/services/services-integrations/src/remote_ssh/remote_fs.rs index 32731e391c..dcb60d86cf 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/remote_fs.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/remote_fs.rs @@ -587,49 +587,12 @@ impl RemoteFileService { manager.sftp_remove(connection_id, path).await } - /// Remove a directory and its contents recursively via SFTP + /// Remove the whole directory on the workspace host with one command. pub async fn remove_dir_all(&self, connection_id: &str, path: &str) -> anyhow::Result<()> { - // Match local remove_dir_all: unlink a final symlink without traversing - // its target. Recheck at every recursive step, including the root. - match self - .workspace_metadata(connection_id, path, false) + self.get_manager(connection_id) .await? - .map(|metadata| metadata.kind) - { - Some(openbitfun_runtime_ports::WorkspacePathKind::Symlink) => { - return self.remove_file(connection_id, path).await - } - Some(openbitfun_runtime_ports::WorkspacePathKind::Directory) => {} - Some(_) => anyhow::bail!("Remote path is not a directory: {path}"), - None => anyhow::bail!("Remote directory does not exist: {path}"), - } - // First, delete all contents - { - let entries = self.read_dir(connection_id, path).await?; - for entry in entries { - let entry_path = entry.path.clone(); - if entry.is_dir && !entry.is_symlink { - Box::pin(self.remove_dir_all(connection_id, &entry_path)).await?; - } else { - let manager = self.get_manager(connection_id).await?; - if manager.is_shell_workspace(connection_id).await { - manager - .container_remove(connection_id, &entry_path, false) - .await?; - } else { - manager.sftp_remove(connection_id, &entry_path).await?; - } - } - } - } - - // Then remove the directory itself - let manager = self.get_manager(connection_id).await?; - if manager.is_shell_workspace(connection_id).await { - manager.container_remove(connection_id, path, true).await - } else { - manager.sftp_rmdir(connection_id, path).await - } + .remove_workspace_directory_all(connection_id, path) + .await } /// Remove an empty directory via SFTP (non-recursive; fails if not empty) diff --git a/src/crates/services/services-integrations/src/remote_ssh/shell.rs b/src/crates/services/services-integrations/src/remote_ssh/shell.rs index 232c500931..28e30397b1 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/shell.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/shell.rs @@ -8,6 +8,33 @@ pub(crate) fn quote_arg(value: &str) -> String { format!("'{}'", value.replace('\'', "'\\''")) } +/// Keep traversal on the target host, without following a final directory link. +#[cfg(feature = "remote-ssh-concrete")] +pub(crate) fn remove_directory_command(path: &str) -> anyhow::Result { + // A trailing slash makes some tools follow a directory symlink. Preserve + // every other byte, including whitespace and POSIX filename backslashes. + let path = path.trim_end_matches('/'); + if !path.starts_with('/') + || path.contains('\0') + || matches!(path.rsplit('/').next(), Some("" | "." | "..")) + { + anyhow::bail!("Recursive deletion requires an absolute non-root directory path"); + } + let script = format!( + "target={}; \ + if [ -L \"$target\" ] || [ -d \"$target\" ]; then \ + exec rm -rf -- \"$target\"; \ + elif [ -e \"$target\" ]; then \ + printf 'Remote path is not a directory: %s\\n' \"$target\" >&2; \ + else \ + printf 'Remote directory does not exist or cannot be accessed: %s\\n' \"$target\" >&2; \ + fi; exit 1", + quote_arg(path), + ); + // The SSH login shell need not itself implement POSIX conditional syntax. + Ok(format!("sh -c {}", quote_arg(&script))) +} + #[cfg(feature = "remote-ssh-concrete")] pub(crate) fn escape_terminal_cwd(value: &str) -> String { if value diff --git a/src/web-ui/src/infrastructure/api/service-api/ApiClient.test.ts b/src/web-ui/src/infrastructure/api/service-api/ApiClient.test.ts index 099278093c..c9e79bf020 100644 --- a/src/web-ui/src/infrastructure/api/service-api/ApiClient.test.ts +++ b/src/web-ui/src/infrastructure/api/service-api/ApiClient.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { ApiClient, createRetryMiddleware } from './ApiClient'; +import { workspaceAPI } from './WorkspaceAPI'; import { LOCAL_SURFACE_ID, SurfaceChangedError, @@ -277,6 +278,29 @@ describe('ApiClient startup trace classification', () => { } }); + it.each(['workspace', 'legacy'] as const)('waits for a long %s directory deletion to finish', async (entry) => { + vi.useFakeTimers(); + try { + let finish!: () => void; + adapterMocks.request.mockReturnValueOnce(new Promise(resolve => { finish = resolve; })); + let settled = false; + const pending = (entry === 'workspace' + ? workspaceAPI.deleteWorkspaceDirectory('remote-workspace', '/large-directory') + : workspaceAPI.deleteDirectory('/large-directory', true, 'ssh-connection')) + .then( + () => { settled = true; }, + error => { settled = true; return error; }, + ); + await vi.advanceTimersByTimeAsync(60_000); + expect(settled).toBe(false); + expect(adapterMocks.request).toHaveBeenCalledTimes(1); + finish(); + await expect(pending).resolves.toBeUndefined(); + } finally { + vi.useRealTimers(); + } + }); + it('uses the message from plain structured Tauri errors', async () => { const transportError = { code: 'worktree_not_found', diff --git a/src/web-ui/src/infrastructure/api/service-api/WorkspaceAPI.ts b/src/web-ui/src/infrastructure/api/service-api/WorkspaceAPI.ts index 06fca565e0..8470e87882 100644 --- a/src/web-ui/src/infrastructure/api/service-api/WorkspaceAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/WorkspaceAPI.ts @@ -3,6 +3,7 @@ import { workspaceScopedRequest } from './legacyWorkspaceCompatibility'; import { api } from './ApiClient'; +import type { ApiRequestConfig } from './types'; import { workspaceIdRequest, workspaceSearchRequest, workspaceWatchRequest } from './legacyWorkspaceCompatibility'; import { globalEventBus } from '@/infrastructure/event-bus'; import { getActiveSurfaceId, getActiveSurfaceScope, SurfaceChangedError } from '@/infrastructure/peer-device/deviceSurface'; @@ -245,11 +246,12 @@ export class WorkspaceAPI { command: string, workspaceId: string, request: Record, + config?: ApiRequestConfig, ): Promise { try { return await invokePrepared(command, async () => ({ request: { ...await workspaceIdRequest(workspaceId, 'workspacePath'), ...request }, - })); + }), config); } catch (error) { throw createTauriCommandError(command, error, { workspaceId, ...request }); } @@ -268,7 +270,14 @@ export class WorkspaceAPI { } async deleteWorkspaceDirectory(workspaceId: string, path: string, recursive: boolean = true): Promise { - await this.invokeWorkspaceFileCommand('delete_directory', workspaceId, { path, recursive }); + // Disk work may outlive the generic 30s UI deadline. Wait for its outcome; + // the selected transport still owns connection and peer RPC deadlines. + await this.invokeWorkspaceFileCommand( + 'delete_directory', + workspaceId, + { path, recursive }, + recursive ? { timeout: 0 } : undefined, + ); } async renameWorkspaceFile(workspaceId: string, oldPath: string, newPath: string): Promise { @@ -360,7 +369,7 @@ export class WorkspaceAPI { try { await api.invoke('delete_directory', { request: { path, recursive, remoteConnectionId } - }); + }, recursive ? { timeout: 0 } : undefined); } catch (error) { throw createTauriCommandError('delete_directory', error, { path, recursive }); }