chitralverma commented on code in PR #7977:
URL: https://github.com/apache/opendal/pull/7977#discussion_r4756958466
##########
core/services/sftp/src/core.rs:
##########
@@ -95,56 +272,247 @@ pub struct Manager {
root: String,
user: Option<String>,
key: Option<String>,
- known_hosts_strategy: KnownHosts,
+ known_hosts_strategy: KnownHostsStrategy,
+ /// Throttles concurrent SSH handshakes, see [`MAX_CONCURRENT_HANDSHAKES`].
+ handshakes: tokio::sync::Semaphore,
}
-impl ManageObject for Manager {
- type Object = Sftp;
- type Error = Error;
+impl Manager {
+ /// Authenticates the session, preferring the configured key and otherwise
+ /// falling back to an SSH agent and the usual default key locations.
+ async fn authenticate(
+ &self,
+ handle: &mut client::Handle<SshHandler>,
+ user: &str,
+ ) -> Result<()> {
+ if let Some(key) = &self.key {
+ let private_key = russh::keys::load_secret_key(key,
None).map_err(|err| {
+ Error::new(ErrorKind::ConfigInvalid, "sftp failed to load
private key")
+ .set_source(err)
+ })?;
+
+ if self
+ .try_publickey(handle, user, private_key)
+ .await?
+ .is_some()
+ {
+ return Ok(());
+ }
- async fn create(&self) -> Result<Self::Object, Self::Error> {
- let mut session = SessionBuilder::default();
+ return Err(Error::new(
+ ErrorKind::PermissionDenied,
+ "sftp public key authentication failed",
+ ));
+ }
- if let Some(user) = &self.user {
- session.user(user.clone());
+ if self.try_agent(handle, user).await? {
+ return Ok(());
}
- if let Some(key) = &self.key {
- session.keyfile(key);
+ for candidate in default_key_paths() {
+ let Ok(private_key) = russh::keys::load_secret_key(&candidate,
None) else {
+ continue;
+ };
+ if self
+ .try_publickey(handle, user, private_key)
+ .await?
+ .is_some()
+ {
+ return Ok(());
+ }
}
- session.known_hosts_check(self.known_hosts_strategy.clone());
+ Err(Error::new(
+ ErrorKind::PermissionDenied,
+ "sftp authentication failed: no usable credentials, set `key` to a
private key path",
+ ))
+ }
+
+ async fn try_publickey(
+ &self,
+ handle: &mut client::Handle<SshHandler>,
+ user: &str,
+ private_key: russh::keys::PrivateKey,
+ ) -> Result<Option<()>> {
+ // RSA keys must be signed with the strongest hash the server accepts;
+ // servers commonly reject the legacy SHA-1 `ssh-rsa` signatures.
+ let hash_alg = handle
+ .best_supported_rsa_hash()
+ .await
+ .map_err(parse_ssh_error)?
+ .flatten();
- let session = session
- .connect(&self.endpoint)
+ let result = handle
+ .authenticate_publickey(
+ user,
+ PrivateKeyWithHashAlg::new(Arc::new(private_key), hash_alg),
+ )
.await
.map_err(parse_ssh_error)?;
- let sftp = Sftp::from_session(session, SftpOptions::default())
+ Ok(result.success().then_some(()))
+ }
+
+ async fn try_agent(&self, handle: &mut client::Handle<SshHandler>, user:
&str) -> Result<bool> {
+ #[cfg(unix)]
+ {
+ use russh::keys::agent::AgentIdentity;
+
+ let Ok(mut agent) =
russh::keys::agent::client::AgentClient::connect_env().await else {
+ return Ok(false);
+ };
+ let Ok(identities) = agent.request_identities().await else {
+ return Ok(false);
+ };
+
+ let hash_alg = handle
+ .best_supported_rsa_hash()
+ .await
+ .map_err(parse_ssh_error)?
+ .flatten();
+
+ // Every attempt counts against the server's `MaxAuthTries` (6 by
+ // default), and exhausting it disconnects instead of reporting a
+ // clean authentication failure.
+ for identity in identities.into_iter().take(MAX_AGENT_IDENTITIES) {
+ let AgentIdentity::PublicKey { key, .. } = identity else {
+ continue;
+ };
+
+ let Ok(result) = handle
+ .authenticate_publickey_with(user, key, hash_alg, &mut
agent)
+ .await
+ else {
+ continue;
+ };
+ if result.success() {
+ return Ok(true);
+ }
+ }
+ }
+
+ let _ = (handle, user);
+ Ok(false)
+ }
+}
+
+impl ManageObject for Manager {
+ type Object = SftpConnection;
+ type Error = Error;
+
+ async fn create(&self) -> Result<Self::Object, Self::Error> {
+ let _permit = self.handshakes.acquire().await.map_err(|err| {
+ Error::new(ErrorKind::Unexpected, "sftp connection limiter
closed").set_source(err)
+ })?;
+
+ let (endpoint_user, host, port) = parse_endpoint(&self.endpoint)?;
+
+ // A user encoded in the endpoint takes precedence over the builder
value.
+ let user = endpoint_user
+ .or_else(|| self.user.clone())
+ .or_else(default_user)
+ .ok_or_else(|| {
+ Error::new(
+ ErrorKind::ConfigInvalid,
+ "sftp user is not set and cannot be inferred from the
environment",
+ )
+ })?;
+
+ let handler = SshHandler {
+ host: host.clone(),
+ port,
+ strategy: self.known_hosts_strategy,
+ };
+
+ let mut handle = client::connect(
Review Comment:
04c34d691: `build()` resolves the endpoint, user, root, strategy, and
`known_hosts` paths. `Manager::create` only connects and authenticates.
*This comment is AI assisted.*
##########
core/services/sftp/src/core.rs:
##########
@@ -75,6 +222,36 @@ impl SftpCore {
}
}
+ /// Resolves an OpenDAL path against the configured root.
Review Comment:
04c34d691: `remote_path` uses `build_rooted_absolute_path` /
`build_absolute_path` from `raw::path`. It only trims the trailing `/`, which
OpenSSH for Windows rejects.
*This comment is AI assisted.*
##########
core/services/sftp/src/core.rs:
##########
@@ -15,18 +15,164 @@
// specific language governing permissions and limitations
// under the License.
+use std::fmt::Debug;
+use std::sync::Arc;
+
use fastpool::{ManageObject, ObjectStatus, bounded};
use log::debug;
use opendal_core::raw::*;
use opendal_core::*;
-use openssh::KnownHosts;
-use openssh::SessionBuilder;
-use openssh_sftp_client::Sftp;
-use openssh_sftp_client::SftpOptions;
-use std::fmt::Debug;
-use std::path::Path;
-use std::path::PathBuf;
-use std::sync::Arc;
+use russh::client;
+use russh::keys::PrivateKeyWithHashAlg;
+use russh_sftp::client::RawSftpSession;
+use russh_sftp::client::rawsession::Limits;
+use russh_sftp::protocol::FileAttributes;
+
+/// Largest payload we ever ask the remote server for in a single SFTP packet.
+///
+/// The effective value is additionally clamped by the limits advertised
through
+/// the `[email protected]` extension.
+const MAX_CHUNK_SIZE: u32 = 256 * 1024;
+
+/// Conservative payload size used when the server does not advertise limits.
+///
+/// SFTP v3 has no negotiation for this, and 32 KiB is the value the OpenSSH
+/// client itself falls back to.
+const DEFAULT_CHUNK_SIZE: u32 = 32 * 1024;
+
+/// Number of SFTP read/write packets kept in flight at once.
+///
+/// SFTP is a request/response protocol, so throughput on links with
non-trivial
+/// latency is bound by the number of outstanding requests rather than
bandwidth.
+pub const PIPELINE_DEPTH: usize = 8;
+
+/// OpenSSH extension providing `rename` with POSIX overwrite semantics.
+pub const POSIX_RENAME: &str = "[email protected]";
+
+/// Number of SSH handshakes allowed to run at the same time.
+///
+/// Servers cap how many connections may be mid-authentication at once
+/// (`MaxStartups` defaults to `10:30:100` in OpenSSH, which starts dropping
+/// connections past ten), so growing the pool in a burst must be throttled.
+const MAX_CONCURRENT_HANDSHAKES: usize = 4;
+
+/// Number of agent identities tried before giving up.
+///
+/// Each attempt counts against the server's `MaxAuthTries`, which defaults to
+/// six in OpenSSH and drops the connection once exceeded.
+#[cfg(unix)]
+const MAX_AGENT_IDENTITIES: usize = 4;
+
+/// Specifies how `SftpBackend` validates the remote host key.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum KnownHostsStrategy {
+ /// The host key must be present in `known_hosts` and match.
+ ///
+ /// This mirrors `ssh -o StrictHostKeyChecking=yes`.
+ Strict,
+ /// Accept a previously unseen host key and record it in `known_hosts`.
+ ///
+ /// A changed key is still rejected. This mirrors
+ /// `ssh -o StrictHostKeyChecking=accept-new`.
+ Add,
+ /// Accept whatever key the server presents.
+ ///
+ /// This mirrors `ssh -o StrictHostKeyChecking=no`.
+ Accept,
+}
+
+/// Validates the remote host key according to [`KnownHostsStrategy`].
+struct SshHandler {
+ host: String,
+ port: u16,
+ strategy: KnownHostsStrategy,
+}
+
+impl client::Handler for SshHandler {
+ type Error = russh::Error;
+
+ async fn check_server_key(
+ &mut self,
+ server_public_key: &russh::keys::ssh_key::PublicKey,
+ ) -> std::result::Result<bool, Self::Error> {
+ match self.strategy {
+ KnownHostsStrategy::Accept => Ok(true),
+ KnownHostsStrategy::Strict => {
+ Ok(
+ russh::keys::check_known_hosts(&self.host, self.port,
server_public_key)
+ .unwrap_or(false),
+ )
+ }
+ KnownHostsStrategy::Add => {
+ match russh::keys::check_known_hosts(&self.host, self.port,
server_public_key) {
+ Ok(true) => Ok(true),
+ // The host is unknown: record it and continue.
+ Ok(false) => {
+ if let Err(err) =
russh::keys::known_hosts::learn_known_hosts(
+ &self.host,
+ self.port,
+ server_public_key,
+ ) {
+ // Nothing was pinned, so every later connection
also
+ // takes this branch and `add` silently behaves
like
+ // `accept`. Surface it rather than hiding it.
+ log::warn!(
+ "sftp accepted host key for {}:{} but could
not record it in known_hosts, \
+ so it will not be verified on future
connections: {err}",
+ self.host,
+ self.port
+ );
+ }
+ Ok(true)
+ }
+ // The host is known but the key changed: refuse to
connect.
+ Err(_) => Ok(false),
+ }
+ }
+ }
+ }
+}
+
+/// A detachable reference to a live SFTP session.
Review Comment:
04c34d691 removes `SftpSessionRef`. Readers, writers, and listers hold the
pooled connection until their handle closes, as on `main` (#8959). `OpenHandle`
owns the handle and an `Arc` of the connection. Dropping it without `close()`
closes the handle on the connection's runtime, then returns the connection to
the pool.
*This comment is AI assisted.*
##########
core/services/sftp/src/core.rs:
##########
@@ -15,18 +15,164 @@
// specific language governing permissions and limitations
// under the License.
+use std::fmt::Debug;
+use std::sync::Arc;
+
use fastpool::{ManageObject, ObjectStatus, bounded};
use log::debug;
use opendal_core::raw::*;
use opendal_core::*;
-use openssh::KnownHosts;
-use openssh::SessionBuilder;
-use openssh_sftp_client::Sftp;
-use openssh_sftp_client::SftpOptions;
-use std::fmt::Debug;
-use std::path::Path;
-use std::path::PathBuf;
-use std::sync::Arc;
+use russh::client;
+use russh::keys::PrivateKeyWithHashAlg;
+use russh_sftp::client::RawSftpSession;
+use russh_sftp::client::rawsession::Limits;
+use russh_sftp::protocol::FileAttributes;
+
+/// Largest payload we ever ask the remote server for in a single SFTP packet.
+///
+/// The effective value is additionally clamped by the limits advertised
through
+/// the `[email protected]` extension.
+const MAX_CHUNK_SIZE: u32 = 256 * 1024;
+
+/// Conservative payload size used when the server does not advertise limits.
+///
+/// SFTP v3 has no negotiation for this, and 32 KiB is the value the OpenSSH
+/// client itself falls back to.
+const DEFAULT_CHUNK_SIZE: u32 = 32 * 1024;
+
+/// Number of SFTP read/write packets kept in flight at once.
+///
+/// SFTP is a request/response protocol, so throughput on links with
non-trivial
+/// latency is bound by the number of outstanding requests rather than
bandwidth.
+pub const PIPELINE_DEPTH: usize = 8;
+
+/// OpenSSH extension providing `rename` with POSIX overwrite semantics.
+pub const POSIX_RENAME: &str = "[email protected]";
+
+/// Number of SSH handshakes allowed to run at the same time.
+///
+/// Servers cap how many connections may be mid-authentication at once
+/// (`MaxStartups` defaults to `10:30:100` in OpenSSH, which starts dropping
+/// connections past ten), so growing the pool in a burst must be throttled.
+const MAX_CONCURRENT_HANDSHAKES: usize = 4;
+
+/// Number of agent identities tried before giving up.
+///
+/// Each attempt counts against the server's `MaxAuthTries`, which defaults to
+/// six in OpenSSH and drops the connection once exceeded.
+#[cfg(unix)]
+const MAX_AGENT_IDENTITIES: usize = 4;
+
+/// Specifies how `SftpBackend` validates the remote host key.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum KnownHostsStrategy {
+ /// The host key must be present in `known_hosts` and match.
+ ///
+ /// This mirrors `ssh -o StrictHostKeyChecking=yes`.
+ Strict,
+ /// Accept a previously unseen host key and record it in `known_hosts`.
+ ///
+ /// A changed key is still rejected. This mirrors
+ /// `ssh -o StrictHostKeyChecking=accept-new`.
+ Add,
+ /// Accept whatever key the server presents.
+ ///
+ /// This mirrors `ssh -o StrictHostKeyChecking=no`.
+ Accept,
+}
+
+/// Validates the remote host key according to [`KnownHostsStrategy`].
+struct SshHandler {
+ host: String,
+ port: u16,
+ strategy: KnownHostsStrategy,
+}
+
+impl client::Handler for SshHandler {
+ type Error = russh::Error;
+
+ async fn check_server_key(
+ &mut self,
+ server_public_key: &russh::keys::ssh_key::PublicKey,
+ ) -> std::result::Result<bool, Self::Error> {
+ match self.strategy {
+ KnownHostsStrategy::Accept => Ok(true),
+ KnownHostsStrategy::Strict => {
+ Ok(
+ russh::keys::check_known_hosts(&self.host, self.port,
server_public_key)
+ .unwrap_or(false),
+ )
+ }
+ KnownHostsStrategy::Add => {
+ match russh::keys::check_known_hosts(&self.host, self.port,
server_public_key) {
Review Comment:
04c34d691 replaces russh's `known_hosts` check with `known_hosts.rs`.
`strict` and `add` reject a changed key, a changed algorithm, a `@revoked` key,
and a file that exists but cannot be read. `add` accepts a new host only after
the append succeeds. `accept` never reads or writes the file, and the docs say
so.
- It reads the files OpenSSH reads (`~/.ssh/known_hosts{,2}`,
`/etc/ssh/ssh_known_hosts{,2}`), writes only the first, and negotiates recorded
key types first, like OpenSSH.
- Unit tests cover first connection, changed key and algorithm, revoked,
unreadable and unwritable files, and hashed and wildcard entries.
- Checked against `atmoz/sftp` with a throwaway `HOME`: unknown, `add` then
`strict`, changed, revoked, hashed, and RSA-only entries.
*This comment is AI assisted.*
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]