Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/features/remote-workspaces.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 12 additions & 12 deletions src/apps/desktop/src/api/ssh_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
6 changes: 6 additions & 0 deletions src/crates/services/services-integrations/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<SSHConnectionManager>,
state: Arc<State>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
27 changes: 27 additions & 0 deletions src/crates/services/services-integrations/src/remote_ssh/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> {
// 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
Expand Down
Loading
Loading