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 74295bfff2..9b2c53fbeb 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/manager.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/manager.rs @@ -3,7 +3,7 @@ //! This module manages SSH connections using the pure-Russ SSH implementation use super::proxy_command::{expand_tokens, ProxyCommandChild}; -use super::sftp_file::ManagedSftpSession; +use super::sftp_file::{ManagedSftpFile, ManagedSftpSession}; #[cfg(feature = "ssh_config")] use super::ssh_config_loader::{ is_host_pattern, load_merged_config_async, resolve_host_settings, split_directive, @@ -26,6 +26,8 @@ use russh_sftp::client::error::Error as SftpError; use russh_sftp::client::{RawSftpSession, SftpSession}; use russh_sftp::protocol::{File as SftpFile, StatusCode as SftpStatusCode}; use std::collections::HashMap; +use std::future::Future; +use std::pin::Pin; use std::process::Stdio; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; @@ -375,7 +377,7 @@ mtime=$(stat -c %Y \"$item\" 2>/dev/null || stat -f %m \"$item\" 2>/dev/null || mode=$(stat -c %a \"$item\" 2>/dev/null || stat -f %Lp \"$item\" 2>/dev/null || true); \ printf '%s\\0%s\\0%s\\0%s\\0%s\\0%s\\0' \"$name\" \"$item\" \"$kind\" \"$size\" \"$mtime\" \"$mode\";"; -fn sftp_error_may_be_stale_transport(error: &SftpError) -> bool { +pub(super) fn sftp_error_may_be_stale_transport(error: &SftpError) -> bool { match error { SftpError::Status(status) => matches!( status.status_code, @@ -671,6 +673,9 @@ struct SftpCache { init_lock: tokio::sync::Mutex<()>, } +/// One replayable request issued against a cached SFTP subsystem. +type SftpRequest = Pin> + Send>>; + impl SftpCache { fn new() -> Self { Self { @@ -5602,11 +5607,9 @@ impl SSHConnectionManager { let transport = self.open_workspace_stdio(connection_id, &command).await?; return Ok(Box::new(ContainerFileReader::from_transport(transport))); } - let sftp = self.get_sftp(connection_id).await?; - let file = sftp - .open(&path) + let file = self + .sftp_open_with_recovery(connection_id, &path) .await - .map_err(anyhow::Error::new) .with_context(|| format!("Failed to open remote file '{path}'"))?; if !file.metadata().await?.file_type().is_file() { anyhow::bail!("Workspace path is not a regular file: {path}"); @@ -6393,6 +6396,58 @@ impl SSHConnectionManager { Ok(sftp) } + /// Replay one read-only request on a fresh subsystem channel. + /// + /// russh-sftp rejects every request on a closed subsystem channel with + /// `UnexpectedBehavior("session closed")` and never reopens it, while + /// `get_sftp` keeps handing out that same cached session. Returning that + /// error left the file browser stuck on `Failed to stat` until the app was + /// restarted. [`ManagedSftpSession`] now retires a session whose channel is + /// gone, so replaying the request once opens a new channel instead of + /// failing forever. Only idempotent queries may use this helper. + async fn sftp_query_with_recovery( + &self, + connection_id: &str, + path: &str, + query: F, + ) -> anyhow::Result + where + F: Fn(Arc, String) -> SftpRequest, + { + let mut replay = true; + loop { + let session = self.get_sftp(connection_id).await?; + match query(session, path.to_owned()).await { + Ok(value) => return Ok(value), + Err(error) if replay && sftp_error_may_be_stale_transport(&error) => { + replay = false; + log::warn!( + "Cached SFTP subsystem for {} failed on '{}' (will retry once on a new channel): {}", + connection_id, + path, + error + ); + } + Err(error) => return Err(anyhow::Error::new(error)), + } + } + } + + /// Open a file read-only, replaying the OPEN once on a fresh subsystem. + /// + /// A read-only OPEN changes nothing on the server and no data has reached + /// the caller yet, so it is as safe to replay as a metadata query. + async fn sftp_open_with_recovery( + &self, + connection_id: &str, + path: &str, + ) -> anyhow::Result { + self.sftp_query_with_recovery(connection_id, path, |sftp, open_path| { + Box::pin(async move { sftp.open(&open_path).await }) + }) + .await + } + /// Reuse a dedicated SFTP channel for serialized directory enumeration. /// The high-level API leaks directory handles on errors/cancellation. The /// raw path closes on all exits and can also stop at an entry budget. @@ -6476,9 +6531,8 @@ impl SSHConnectionManager { /// Read a file via SFTP pub async fn sftp_read(&self, connection_id: &str, path: &str) -> anyhow::Result> { let path = self.resolve_sftp_path(connection_id, path).await?; - let sftp = self.get_sftp(connection_id).await?; - let mut file = sftp - .open(&path) + let mut file = self + .sftp_open_with_recovery(connection_id, &path) .await .map_err(|e| anyhow!("Failed to open remote file '{}': {}", path, e))?; @@ -6507,18 +6561,18 @@ impl SSHConnectionManager { on_progress: &mut impl FnMut(u64, u64) -> bool, ) -> anyhow::Result> { let resolved = self.resolve_sftp_path(connection_id, path).await?; - let sftp = self.get_sftp(connection_id).await?; // Determine file size from metadata for progress calculation. - let metadata = sftp - .as_ref() - .metadata(&resolved) + let metadata = self + .sftp_query_with_recovery(connection_id, &resolved, |sftp, query_path| { + Box::pin(async move { sftp.as_ref().metadata(&query_path).await }) + }) .await .map_err(|e| anyhow!("Failed to stat '{}': {}", resolved, e))?; let total = metadata.size.unwrap_or(0); - let mut file = sftp - .open(&resolved) + let mut file = self + .sftp_open_with_recovery(connection_id, &resolved) .await .map_err(|e| anyhow!("Failed to open remote file '{}': {}", resolved, e))?; @@ -6904,16 +6958,37 @@ impl SSHConnectionManager { /// Create directory and all parents via SFTP pub async fn sftp_mkdir_all(&self, connection_id: &str, path: &str) -> anyhow::Result<()> { let path = self.resolve_sftp_path(connection_id, path).await?; + // Every step accepts directories that already exist, so a whole attempt + // can be replayed once after a dead cached subsystem was retired. + match self.sftp_mkdir_all_once(connection_id, &path).await { + Err(error) + if error + .downcast_ref::() + .is_some_and(sftp_error_may_be_stale_transport) => + { + log::warn!( + "Cached SFTP subsystem for {} failed creating '{}' (will retry once on a new channel): {:#}", + connection_id, + path, + error + ); + self.sftp_mkdir_all_once(connection_id, &path).await + } + result => result, + } + } + + async fn sftp_mkdir_all_once(&self, connection_id: &str, path: &str) -> anyhow::Result<()> { let sftp = self.get_sftp(connection_id).await?; // Check if path exists - match sftp.as_ref().try_exists(&path).await { + match sftp.as_ref().try_exists(path).await { Ok(true) => return Ok(()), // Already exists Ok(false) => {} Err(_) => {} } - for dir in sftp_mkdir_all_prefixes(&path) { + for dir in sftp_mkdir_all_prefixes(path) { if let Ok(true) = sftp.as_ref().try_exists(&dir).await { continue; } @@ -6922,7 +6997,8 @@ impl SSHConnectionManager { match sftp.as_ref().try_exists(&dir).await { Ok(true) => continue, Ok(false) | Err(_) => { - return Err(anyhow!("Failed to create directory '{}': {}", dir, error)); + let message = format!("Failed to create directory '{}': {}", dir, error); + return Err(anyhow::Error::new(error).context(message)); } } } @@ -6970,11 +7046,11 @@ impl SSHConnectionManager { /// Check if path exists via SFTP pub async fn sftp_exists(&self, connection_id: &str, path: &str) -> anyhow::Result { let path = self.resolve_sftp_path(connection_id, path).await?; - let sftp = self.get_sftp(connection_id).await?; - sftp.as_ref() - .try_exists(&path) - .await - .map_err(|e| anyhow!("Failed to check if '{}' exists: {}", path, e)) + self.sftp_query_with_recovery(connection_id, &path, |sftp, query_path| { + Box::pin(async move { sftp.as_ref().try_exists(&query_path).await }) + }) + .await + .map_err(|e| anyhow!("Failed to check if '{}' exists: {}", path, e)) } /// Get file metadata via SFTP @@ -6984,10 +7060,13 @@ impl SSHConnectionManager { path: &str, ) -> anyhow::Result { let path = self.resolve_sftp_path(connection_id, path).await?; - let sftp = self.get_sftp(connection_id).await?; - sftp.as_ref().metadata(&path).await.map_err(|error| { + self.sftp_query_with_recovery(connection_id, &path, |sftp, query_path| { + Box::pin(async move { sftp.as_ref().metadata(&query_path).await }) + }) + .await + .map_err(|error| { let message = format!("Failed to stat '{}': {}", path, error); - anyhow::Error::new(error).context(message) + error.context(message) }) } @@ -6998,12 +7077,11 @@ impl SSHConnectionManager { path: &str, ) -> anyhow::Result { let path = self.resolve_sftp_path(connection_id, path).await?; - let sftp = self.get_sftp(connection_id).await?; - sftp.as_ref() - .symlink_metadata(&path) - .await - .map_err(anyhow::Error::new) - .with_context(|| format!("Failed to inspect '{}'", path)) + self.sftp_query_with_recovery(connection_id, &path, |sftp, query_path| { + Box::pin(async move { sftp.as_ref().symlink_metadata(&query_path).await }) + }) + .await + .with_context(|| format!("Failed to inspect '{}'", path)) } // ============================================================================ 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 2d9e75dd89..ad69759261 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 @@ -22,11 +22,79 @@ struct State { fail_read: AtomicBool, fail_write: AtomicBool, fail_close: AtomicBool, + kill_sftp: Arc, requested: tokio::sync::Notify, release: tokio::sync::Notify, response_delay_ms: std::sync::atomic::AtomicU64, } +/// Cuts an in-memory SFTP transport on demand. +#[derive(Default)] +struct KillSwitch { + killed: AtomicBool, + waker: std::sync::Mutex>, +} + +impl KillSwitch { + fn kill(&self) { + self.killed.store(true, Ordering::SeqCst); + let waker = self.waker.lock().unwrap().take(); + if let Some(waker) = waker { + // A pending read has to observe the new state without a packet. + waker.wake(); + } + } +} + +/// Server side of an in-memory SFTP transport that can be cut on demand. +/// +/// Ending the server's read loop drops its channel, which is what a server-side +/// subsystem close leaves behind. +struct KillableStream { + inner: S, + switch: Arc, +} + +impl tokio::io::AsyncRead for KillableStream { + fn poll_read( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + buf: &mut tokio::io::ReadBuf<'_>, + ) -> std::task::Poll> { + if self.switch.killed.load(Ordering::SeqCst) { + return std::task::Poll::Ready(Ok(())); + } + if let Ok(mut waker) = self.switch.waker.lock() { + *waker = Some(cx.waker().clone()); + } + std::pin::Pin::new(&mut self.inner).poll_read(cx, buf) + } +} + +impl tokio::io::AsyncWrite for KillableStream { + fn poll_write( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + buf: &[u8], + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.inner).poll_write(cx, buf) + } + + fn poll_flush( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.inner).poll_flush(cx) + } + + fn poll_shutdown( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.inner).poll_shutdown(cx) + } +} + struct SftpServer { state: Arc, handles: HashMap, @@ -176,6 +244,12 @@ impl russh_sftp::server::Handler for SftpServer { attrs: metadata(), }) } + async fn lstat(&mut self, id: u32, _path: String) -> Result { + Ok(Attrs { + id, + attrs: metadata(), + }) + } async fn fstat(&mut self, id: u32, _handle: String) -> Result { Ok(Attrs { id, @@ -1088,6 +1162,106 @@ async fn a_directory_waiter_detects_retirement_after_acquiring_the_lock() { assert_eq!(f.state.opened.load(Ordering::SeqCst), 1); } +/// Serve SFTP over an in-memory transport and cache that session, so a test +/// can kill its channel without disturbing the SSH transport. +async fn cache_killable_sftp_session(f: &Fixture) -> Arc { + let (client_io, server_io) = tokio::io::duplex(64 * 1024); + let handler = SftpServer { + state: f.state.clone(), + handles: HashMap::new(), + data: vec![0, 1, 254, 255], + }; + let server_stream = KillableStream { + inner: server_io, + switch: f.state.kill_sftp.clone(), + }; + tokio::spawn(russh_sftp::server::run(server_stream, handler)); + let session = SftpSession::new_with_config(client_io, sftp_client_config()) + .await + .unwrap(); + let cached = Arc::new(ManagedSftpSession::new(session)); + { + let connections = f.manager.connections.read().await; + let connection = connections.get("sftp-test").unwrap(); + *connection.sftp_session.session.write().await = Some(cached.clone()); + } + f.manager.sftp_stat("sftp-test", "/file").await.unwrap(); + assert_eq!(f.state.channels.load(Ordering::SeqCst), 0); + cached +} + +/// Kill the channel underneath a cached session the manager still considers +/// usable. A server-side close leaves exactly this state: russh-sftp answers +/// every later request with "session closed" while the SSH transport and the +/// cache entry stay alive. The raw session is used on purpose here, because +/// the managed wrapper is what retires a dead subsystem. +async fn kill_cached_sftp_channel(f: &Fixture, cached: &ManagedSftpSession) { + f.state.kill_sftp.kill(); + let raw: &SftpSession = cached; + // A request in flight when the channel dies never completes, so every probe + // is bounded and repeated until russh-sftp reports the closed session. + tokio::time::timeout(Duration::from_secs(5), async { + loop { + match tokio::time::timeout(Duration::from_millis(100), raw.metadata("/file")).await { + Ok(Ok(_)) | Err(_) => continue, + Ok(Err(error)) => { + assert!( + sftp_error_may_be_stale_transport(&error), + "unexpected SFTP failure: {error}" + ); + break; + } + } + } + }) + .await + .expect("the closed subsystem channel never surfaced to the cached session"); + assert!(!cached.is_retired()); +} + +#[tokio::test] +async fn a_closed_subsystem_channel_is_replaced_instead_of_failing_forever() { + let f = Fixture::new().await; + let cached = cache_killable_sftp_session(&f).await; + kill_cached_sftp_channel(&f, &cached).await; + + // A dead cached subsystem must not poison metadata queries: the manager + // retires it and opens a new channel on the same SSH transport. + let metadata = f.manager.sftp_stat("sftp-test", "/file").await.unwrap(); + assert_eq!(metadata.size, Some(4)); + assert_eq!(f.state.channels.load(Ordering::SeqCst), 1); + assert!(f.manager.sftp_exists("sftp-test", "/file").await.unwrap()); + f.manager.sftp_lstat("sftp-test", "/file").await.unwrap(); + assert_eq!(f.state.channels.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn a_read_after_the_subsystem_channel_closed_replays_its_open() { + let f = Fixture::new().await; + let cached = cache_killable_sftp_session(&f).await; + kill_cached_sftp_channel(&f, &cached).await; + + assert_eq!( + f.manager.sftp_read("sftp-test", "/file").await.unwrap(), + vec![0, 1, 254, 255] + ); + assert!(cached.is_retired()); + assert_eq!(f.state.channels.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn mkdir_all_after_the_subsystem_channel_closed_replays_on_a_new_channel() { + let f = Fixture::new().await; + let cached = cache_killable_sftp_session(&f).await; + kill_cached_sftp_channel(&f, &cached).await; + + // The fixture reports every path as existing, so a healthy channel + // finishes without CREATE; the dead one fails every step instead. + f.manager.sftp_mkdir_all("sftp-test", "/a/b").await.unwrap(); + assert!(cached.is_retired()); + assert_eq!(f.state.channels.load(Ordering::SeqCst), 1); +} + #[tokio::test] #[ignore = "Set OPENBITFUN_TEST_SFTP_SERVER to the OpenSSH sftp-server executable"] async fn openssh_streaming_upload_create_is_exclusive_and_closes_handle() { diff --git a/src/crates/services/services-integrations/src/remote_ssh/sftp_file.rs b/src/crates/services/services-integrations/src/remote_ssh/sftp_file.rs index e6296e98ee..0d4c35689d 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/sftp_file.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/sftp_file.rs @@ -2,11 +2,13 @@ //! //! russh-sftp 2.3 File::drop sends CLOSE without decrementing the client's //! handle counter. Explicit shutdown is required even for read-only files. +use super::manager::sftp_error_may_be_stale_transport; use russh_sftp::client::{ error::Error, fs::{File, Metadata}, SftpSession, }; +use russh_sftp::protocol::FileAttributes; use std::{ io, pin::Pin, @@ -59,6 +61,58 @@ impl ManagedSftpSession { self.open_owned(path, 2).await } + /// Record that a request found this subsystem's channel unusable. + /// + /// russh-sftp never revives a session whose writer task stopped: it answers + /// every later request with `UnexpectedBehavior("session closed")`. Without + /// this flag the manager would keep serving the dead cached session, so one + /// closed channel would fail every file operation until the app restarts. + /// Marking it retired makes the next request open a new subsystem channel. + fn record(&self, result: Result) -> Result { + if let Err(error) = &result { + if sftp_error_may_be_stale_transport(error) { + self.retired.store(true, Ordering::Release); + } + } + result + } + + pub(super) async fn metadata(&self, path: &str) -> Result { + self.record(self.session.metadata(path).await) + } + + pub(super) async fn symlink_metadata(&self, path: &str) -> Result { + self.record(self.session.symlink_metadata(path).await) + } + + pub(super) async fn try_exists(&self, path: &str) -> Result { + self.record(self.session.try_exists(path).await) + } + + pub(super) async fn create_dir(&self, path: &str) -> Result<(), Error> { + self.record(self.session.create_dir(path).await) + } + + pub(super) async fn remove_file(&self, path: &str) -> Result<(), Error> { + self.record(self.session.remove_file(path).await) + } + + pub(super) async fn remove_dir(&self, path: &str) -> Result<(), Error> { + self.record(self.session.remove_dir(path).await) + } + + pub(super) async fn rename(&self, old_path: &str, new_path: &str) -> Result<(), Error> { + self.record(self.session.rename(old_path, new_path).await) + } + + pub(super) async fn set_metadata( + &self, + path: &str, + attributes: FileAttributes, + ) -> Result<(), Error> { + self.record(self.session.set_metadata(path, attributes).await) + } + async fn open_owned(self: &Arc, path: &str, mode: u8) -> Result { let session = self.clone(); let path = path.to_owned();