rcom/tests/ssh_backend.rs

386 lines
12 KiB
Rust
Raw Permalink Normal View History

use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::{Notify, Semaphore};
use async_trait::async_trait;
use openssh_sftp_client::error::SftpErrorKind;
use rcom::domain::{Entry, EntryKind, HostAlias, Location};
use rcom::fs::{BackendRegistry, FsError, ReadFileSystem, ReadPrefix};
use rcom::ssh::connection::SshConnector;
use rcom::ssh::{
ConnectionManager, SftpTransport, SshFs, SshPolicy, map_openssh_error, map_sftp_error_kind,
};
struct StubTransport {
calls: Arc<Mutex<Vec<PathBuf>>>,
}
#[async_trait]
impl SftpTransport for StubTransport {
async fn canonicalize(&self, path: &Path) -> Result<PathBuf, FsError> {
self.calls.lock().unwrap().push(path.to_path_buf());
Ok(PathBuf::from("/home/test"))
}
async fn list(&self, path: &Path) -> Result<Vec<Entry>, FsError> {
self.calls.lock().unwrap().push(path.to_path_buf());
Ok(vec![Entry::new("remote", EntryKind::Directory)])
}
async fn metadata(&self, path: &Path) -> Result<Entry, FsError> {
self.calls.lock().unwrap().push(path.to_path_buf());
Ok(Entry::new("remote", EntryKind::File))
}
async fn read_prefix(&self, path: &Path, limit: usize) -> Result<ReadPrefix, FsError> {
self.calls.lock().unwrap().push(path.to_path_buf());
Ok(ReadPrefix {
data: vec![b'x'; limit.min(3)],
truncated: limit < 3,
})
}
}
#[tokio::test]
async fn sftp_adapter_uses_typed_paths_and_rejects_mixed_sources() {
let calls = Arc::new(Mutex::new(Vec::new()));
let backend = SshFs::new(
HostAlias::new("edge"),
Arc::new(StubTransport {
calls: calls.clone(),
}),
);
let location = Location::ssh(HostAlias::new("edge"), "/srv/odd path;$()");
assert_eq!(backend.list(&location).await.unwrap()[0].name, "remote");
assert_eq!(
backend.canonicalize(&location).await.unwrap().path(),
Path::new("/home/test")
);
assert_eq!(
backend.metadata(&location).await.unwrap().kind,
EntryKind::File
);
assert_eq!(backend.read_prefix(&location, 2).await.unwrap().data, b"xx");
assert!(
calls
.lock()
.unwrap()
.iter()
.all(|path| path == location.path())
);
let wrong_host = Location::ssh(HostAlias::new("other"), "/srv");
let local = Location::local("/srv");
assert!(matches!(
backend.list(&wrong_host).await,
Err(FsError::Disconnected)
));
assert!(matches!(
backend.list(&local).await,
Err(FsError::Disconnected)
));
}
#[test]
fn ssh_policy_is_strict_and_non_interactive() {
let policy = SshPolicy::default();
assert!(policy.strict_host_key);
assert!(policy.batch_mode);
assert_eq!(policy.connect_timeout.as_secs(), 10);
assert_eq!(policy.server_alive_interval.as_secs(), 15);
}
#[test]
fn connect_not_found_reports_missing_system_openssh() {
let missing_openssh = openssh::Error::Connect(io::Error::new(
io::ErrorKind::NotFound,
"No such file or directory (os error 2)",
));
assert_eq!(
map_openssh_error(&missing_openssh),
FsError::Unsupported("system OpenSSH not found".into())
);
}
#[test]
fn openssh_and_sftp_errors_are_mapped_to_safe_categories() {
let host_key = openssh::Error::Connect(io::Error::new(
io::ErrorKind::ConnectionAborted,
"Host key verification failed",
));
let auth = openssh::Error::Connect(io::Error::new(
io::ErrorKind::PermissionDenied,
"Permission denied (publickey)",
));
let timeout = openssh::Error::Connect(io::Error::new(io::ErrorKind::TimedOut, "timeout"));
assert_eq!(map_openssh_error(&host_key), FsError::HostKeyRejected);
assert_eq!(map_openssh_error(&auth), FsError::AuthFailed);
assert_eq!(map_openssh_error(&timeout), FsError::Timeout);
assert_eq!(
map_openssh_error(&openssh::Error::Disconnected),
FsError::Disconnected
);
assert!(matches!(
rcom::ssh::map_sftp_error(openssh_sftp_client::Error::UnsupportedSftpProtocol {
version: 4,
}),
FsError::Unsupported(_)
));
assert_eq!(
map_sftp_error_kind(SftpErrorKind::NoSuchFile),
FsError::NotFound
);
assert_eq!(
map_sftp_error_kind(SftpErrorKind::PermDenied),
FsError::PermissionDenied
);
}
struct StubFs {
host: HostAlias,
}
#[async_trait]
impl ReadFileSystem for StubFs {
async fn list(&self, _location: &Location) -> Result<Vec<Entry>, FsError> {
Ok(vec![Entry::new(self.host.as_str(), EntryKind::Directory)])
}
async fn canonicalize(&self, _location: &Location) -> Result<Location, FsError> {
Ok(Location::ssh(
self.host.clone(),
format!("/home/{}", self.host.as_str()),
))
}
async fn metadata(&self, _location: &Location) -> Result<Entry, FsError> {
Ok(Entry::new(self.host.as_str(), EntryKind::Directory))
}
async fn read_prefix(
&self,
_location: &Location,
_limit: usize,
) -> Result<ReadPrefix, FsError> {
Ok(ReadPrefix::default())
}
}
struct ScriptedConnector {
attempts: Arc<AtomicUsize>,
failures: Arc<Mutex<HashMap<String, FsError>>>,
}
#[async_trait]
impl SshConnector for ScriptedConnector {
async fn connect(&self, host: &HostAlias) -> Result<Arc<dyn ReadFileSystem>, FsError> {
self.attempts.fetch_add(1, Ordering::SeqCst);
if let Some(error) = self.failures.lock().unwrap().remove(host.as_str()) {
return Err(error);
}
Ok(Arc::new(StubFs { host: host.clone() }))
}
}
type FailureMap = Arc<Mutex<HashMap<String, FsError>>>;
type ManagerFixture = (ConnectionManager, Arc<AtomicUsize>, FailureMap);
fn manager() -> ManagerFixture {
let attempts = Arc::new(AtomicUsize::new(0));
let failures = Arc::new(Mutex::new(HashMap::new()));
let connector = Arc::new(ScriptedConnector {
attempts: attempts.clone(),
failures: failures.clone(),
});
let registry = BackendRegistry::new(Arc::new(StubFs {
host: HostAlias::new("local"),
}));
(
ConnectionManager::new(connector, registry),
attempts,
failures,
)
}
#[tokio::test]
async fn connection_is_shared_and_reconnect_changes_epoch() {
let (manager, attempts, _) = manager();
let host = HostAlias::new("edge");
let first = manager.connect(&host).await.unwrap();
let shared = manager.connect(&host).await.unwrap();
assert_eq!(attempts.load(Ordering::SeqCst), 1);
assert_eq!(first.epoch, shared.epoch);
assert_eq!(first.home.path(), Path::new("/home/edge"));
let old_epoch = first.epoch;
assert!(manager.resolve(&first.home, Some(old_epoch)).await.is_ok());
manager.invalidate_if_epoch(&host, old_epoch).await;
assert!(manager.current(&host).await.is_none());
assert!(matches!(
manager.registry().backend(&first.home),
Err(FsError::Disconnected)
));
let reconnected = manager.connect(&host).await.unwrap();
assert!(reconnected.epoch > old_epoch);
assert_eq!(attempts.load(Ordering::SeqCst), 2);
assert!(matches!(
manager.resolve(&reconnected.home, Some(old_epoch)).await,
Err(FsError::Disconnected)
));
assert!(
manager
.resolve(&reconnected.home, Some(reconnected.epoch))
.await
.is_ok()
);
let local = Location::local("/tmp");
assert!(manager.resolve(&local, None).await.is_ok());
}
#[tokio::test]
async fn stale_epoch_invalidation_preserves_current_cache_and_registry() {
let (manager, attempts, _) = manager();
let host = HostAlias::new("edge");
let first = manager.connect(&host).await.unwrap();
manager.invalidate_if_epoch(&host, first.epoch).await;
let reconnected = manager.connect(&host).await.unwrap();
manager.invalidate_if_epoch(&host, first.epoch).await;
assert_eq!(
manager.current(&host).await.unwrap().epoch,
reconnected.epoch
);
assert!(manager.registry().backend(&reconnected.home).is_ok());
assert!(
manager
.resolve(&reconnected.home, Some(reconnected.epoch))
.await
.is_ok()
);
assert_eq!(attempts.load(Ordering::SeqCst), 2);
}
#[tokio::test]
async fn connection_failures_do_not_replace_other_endpoints() {
let (manager, _, failures) = manager();
let edge = HostAlias::new("edge");
let backup = HostAlias::new("backup");
let edge_connection = manager.connect(&edge).await.unwrap();
failures
.lock()
.unwrap()
.insert(backup.to_string(), FsError::AuthFailed);
assert!(matches!(
manager.connect(&backup).await,
Err(FsError::AuthFailed)
));
assert!(manager.current(&edge).await.is_some());
assert_eq!(
manager.current(&edge).await.unwrap().epoch,
edge_connection.epoch
);
assert!(manager.current(&backup).await.is_none());
}
struct BlockingFs {
host: HostAlias,
started: Arc<AtomicUsize>,
started_notify: Arc<Notify>,
release: Arc<Semaphore>,
}
#[async_trait]
impl ReadFileSystem for BlockingFs {
async fn list(&self, _location: &Location) -> Result<Vec<Entry>, FsError> {
self.started.fetch_add(1, Ordering::SeqCst);
self.started_notify.notify_waiters();
let _permit = self
.release
.acquire()
.await
.map_err(|_| FsError::Cancelled)?;
Ok(Vec::new())
}
async fn canonicalize(&self, _location: &Location) -> Result<Location, FsError> {
Ok(Location::ssh(self.host.clone(), "/home/blocked"))
}
async fn metadata(&self, _location: &Location) -> Result<Entry, FsError> {
Ok(Entry::new("blocked", EntryKind::Directory))
}
async fn read_prefix(
&self,
_location: &Location,
_limit: usize,
) -> Result<ReadPrefix, FsError> {
Ok(ReadPrefix::default())
}
}
struct BlockingConnector {
backend: Arc<BlockingFs>,
}
#[async_trait]
impl SshConnector for BlockingConnector {
async fn connect(&self, _host: &HostAlias) -> Result<Arc<dyn ReadFileSystem>, FsError> {
Ok(self.backend.clone())
}
}
#[tokio::test]
async fn endpoint_reads_are_bounded_to_eight_concurrent_operations() {
let started = Arc::new(AtomicUsize::new(0));
let started_notify = Arc::new(Notify::new());
let release = Arc::new(Semaphore::new(0));
let backend = Arc::new(BlockingFs {
host: HostAlias::new("edge"),
started: started.clone(),
started_notify: started_notify.clone(),
release: release.clone(),
});
let registry = BackendRegistry::new(Arc::new(StubFs {
host: HostAlias::new("local"),
}));
let manager = ConnectionManager::new(Arc::new(BlockingConnector { backend }), registry);
let connection = manager.connect(&HostAlias::new("edge")).await.unwrap();
let backend = connection.backend();
let location = connection.home.clone();
let mut tasks = tokio::task::JoinSet::new();
for _ in 0..9 {
let backend = backend.clone();
let location = location.clone();
tasks.spawn(async move { backend.list(&location).await });
}
tokio::time::timeout(Duration::from_secs(2), async {
while started.load(Ordering::SeqCst) < 8 {
started_notify.notified().await;
}
})
.await
.expect("eight reads should start");
tokio::task::yield_now().await;
assert_eq!(started.load(Ordering::SeqCst), 8, "ninth read must wait");
release.add_permits(9);
while let Some(result) = tasks.join_next().await {
result.expect("read task must not panic").unwrap();
}
assert_eq!(started.load(Ordering::SeqCst), 9);
}