diff --git a/crates/tunal-net/src/auth.rs b/crates/tunal-net/src/auth.rs index 003f72f..f525499 100644 --- a/crates/tunal-net/src/auth.rs +++ b/crates/tunal-net/src/auth.rs @@ -127,20 +127,21 @@ pub(crate) async fn authenticate( .flatten() .flatten(); + let mut tried = Tried::default(); if matches!(pref, AuthPref::Any | AuthPref::Agent) - && try_agent(handle, user, resolved, &files, rsa_hash).await + && try_agent(handle, user, resolved, &files, rsa_hash, &mut tried).await { return Ok(()); } if *pref != AuthPref::Agent { for file in &files { - if try_key_file(handle, user, file, rsa_hash, prompts).await { + if try_key_file(handle, user, file, rsa_hash, prompts, &mut tried).await { return Ok(()); } } } if matches!(pref, AuthPref::Agent | AuthPref::Key(_)) { - return Err(denied()); + return Err(tried.denied(host)); } let methods = match handle.authenticate_none(user).await { @@ -148,7 +149,7 @@ pub(crate) async fn authenticate( Ok(russh::client::AuthResult::Failure { remaining_methods, .. }) => remaining_methods, - _ => return Err(denied()), + _ => return Err(tried.denied(host)), }; if methods.contains(&MethodKind::Password) { for _ in 0..MAX_TRIES { @@ -156,26 +157,54 @@ pub(crate) async fn authenticate( let Some(Some(password)) = ask(prompts, move |p| p.password(&u, &h)).await else { break; }; + tried.password = true; match handle .authenticate_password(user, password.expose_secret()) .await { Ok(r) if r.success() => return Ok(()), Ok(_) => {} - Err(e) => return Err(Error::Remote(e.to_string())), + Err(_) => return Err(Error::Remote(format!("{host} closed the connection"))), } } } if methods.contains(&MethodKind::KeyboardInteractive) - && try_interactive(handle, user, prompts).await + && try_interactive(handle, user, prompts, &mut tried).await { return Ok(()); } - Err(denied()) + Err(tried.denied(host)) } -fn denied() -> Error { - Error::Remote("authentication failed".into()) +/// What the sign-in offered the server, for a specific error. +#[derive(Default)] +struct Tried { + /// A public key was offered (agent or file). + key: bool, + /// A key file stayed locked: no passphrase or a wrong one. + locked: Option, + /// A password or keyboard-interactive answer was sent. + password: bool, +} + +impl Tried { + fn denied(&self, host: &str) -> Error { + let name = |p: &Path| { + p.file_name() + .unwrap_or_default() + .to_string_lossy() + .into_owned() + }; + Error::Remote(if self.password { + format!("{host} didn't accept the password") + } else if self.key { + format!("{host} didn't accept the key") + } else if let Some(file) = &self.locked { + format!("the key {} wasn't unlocked", name(file)) + } else { + format!("no key or password to sign in to {host}") + }) + } } /// Identity files to try: the configured ones, else the usual defaults that exist. @@ -205,6 +234,7 @@ async fn try_agent( resolved: &Resolved, files: &[PathBuf], rsa_hash: Option, + tried: &mut Tried, ) -> bool { let Ok(mut agent) = AgentClient::connect_env().await else { return false; @@ -225,6 +255,7 @@ async fn try_agent( continue; } let hash = key.algorithm().is_rsa().then_some(rsa_hash).flatten(); + tried.key = true; if let Ok(r) = handle .authenticate_publickey_with(user, key, hash, &mut agent) .await @@ -242,14 +273,16 @@ async fn try_key_file( file: &Path, rsa_hash: Option, prompts: &Arc, + tried: &mut Tried, ) -> bool { let mut key = keys::load_secret_key(file, None); - if matches!(key, Err(keys::Error::KeyIsEncrypted)) { + let encrypted = matches!(key, Err(keys::Error::KeyIsEncrypted)); + if encrypted { // A wrong passphrase fails with another error, so ask again until the tries run out. for _ in 0..MAX_TRIES { let path = file.to_path_buf(); let Some(Some(pass)) = ask(prompts, move |p| p.passphrase(&path)).await else { - return false; + break; }; key = keys::load_secret_key(file, Some(pass.expose_secret())); if key.is_ok() { @@ -257,7 +290,13 @@ async fn try_key_file( } } } - let Ok(key) = key else { return false }; + let Ok(key) = key else { + if encrypted { + tried.locked = Some(file.to_path_buf()); + } + return false; + }; + tried.key = true; let key = PrivateKeyWithHashAlg::new(Arc::new(key), rsa_hash); matches!(handle.authenticate_publickey(user, key).await, Ok(r) if r.success()) } @@ -266,6 +305,7 @@ async fn try_interactive( handle: &mut Handle, user: &str, prompts: &Arc, + tried: &mut Tried, ) -> bool { let Ok(mut response) = handle .authenticate_keyboard_interactive_start(user, None) @@ -299,6 +339,7 @@ async fn try_interactive( let Some(Some(a)) = ask(prompts, move |p| p.interactive(&req)).await else { return false; }; + tried.password = true; a.iter().map(|s| s.expose_secret().to_owned()).collect() }; match handle diff --git a/crates/tunal-net/src/session.rs b/crates/tunal-net/src/session.rs index 2ca3a6e..be7affa 100644 --- a/crates/tunal-net/src/session.rs +++ b/crates/tunal-net/src/session.rs @@ -6,9 +6,11 @@ use std::future::Future; use std::sync::{Arc, Mutex, OnceLock}; use std::time::{Duration, Instant}; +use russh::ChannelMsg; use russh::client::{self, Handle}; use russh::keys::{HashAlg, PublicKeyOrCertificate}; use russh_sftp::client::SftpSession; +use russh_sftp::client::error::Error as SftpError; use tokio::runtime::Runtime; use tunal_core::{Error, Result}; @@ -104,13 +106,18 @@ impl Conn { /// Connection pool. Cheap to clone via `Arc`. pub(crate) struct Pool { conns: Mutex>>, + /// Held while connecting to a key; holds the last failed attempt and when it ended. + attempts: Mutex>>>, prompts: Arc, } +type Attempt = Option<(Instant, Error)>; + impl Pool { pub fn new(prompts: Arc) -> Arc { let pool = Arc::new(Self { conns: Mutex::default(), + attempts: Mutex::default(), prompts, }); let weak = Arc::downgrade(&pool); @@ -124,15 +131,47 @@ impl Pool { pool } - /// A live connection for `key`, connecting (and authenticating) when needed. + /// A live connection for `key`, connecting (and authenticating) when needed. One attempt + /// per key at a time: callers that waited for it share its connection or its error. pub fn get(&self, key: &ConnKey, resolved: &Resolved, pref: &AuthPref) -> Result> { - if let Some(c) = self.conns.lock().unwrap().get(key).filter(|c| c.alive()) { - c.touch(); - return Ok(c.clone()); + let asked = Instant::now(); + if let Some(c) = self.live(key) { + return Ok(c); } - let conn = block_on(connect(key, resolved, pref, &self.prompts))?; - self.conns.lock().unwrap().insert(key.clone(), conn.clone()); - Ok(conn) + let slot = self + .attempts + .lock() + .unwrap() + .entry(key.clone()) + .or_default() + .clone(); + let mut last = slot.lock().unwrap(); + if let Some(c) = self.live(key) { + return Ok(c); + } + if let Some((at, e)) = &*last + && *at >= asked + { + return Err(e.clone()); + } + match block_on(connect(key, resolved, pref, &self.prompts)) { + Ok(conn) => { + *last = None; + self.conns.lock().unwrap().insert(key.clone(), conn.clone()); + Ok(conn) + } + Err(e) => { + *last = Some((Instant::now(), e.clone())); + Err(e) + } + } + } + + fn live(&self, key: &ConnKey) -> Option> { + let conns = self.conns.lock().unwrap(); + let c = conns.get(key).filter(|c| c.alive())?; + c.touch(); + Some(c.clone()) } /// Forgets a connection that failed mid-operation so the next `get` reconnects. @@ -205,33 +244,21 @@ async fn connect( prompts: prompts.clone(), failure: failure.clone(), }; + // Messages name the host as the user wrote it (an ssh config alias, say). + let name = resolved.alias.as_str(); let connecting = client::connect(config, (key.host.as_str(), key.port), client); let mut handle = match tokio::time::timeout(opts.connect_timeout, connecting).await { - Err(_) => { - return Err(Error::Remote(format!( - "connecting to {} timed out", - key.host - ))); - } + Err(_) => return Err(Error::Remote(format!("connecting to {name} timed out"))), Ok(Err(e)) => { let reason = failure.lock().unwrap().take(); - return Err(Error::Remote(reason.unwrap_or_else(|| why(&e, &key.host)))); + return Err(Error::Remote(reason.unwrap_or_else(|| why(&e, name)))); } Ok(Ok(h)) => h, }; - authenticate(&mut handle, &key.user, &key.host, resolved, pref, prompts).await?; - let remote = |e: &dyn std::fmt::Display| Error::Remote(e.to_string()); - let channel = handle - .channel_open_session() + authenticate(&mut handle, &key.user, name, resolved, pref, prompts).await?; + let sftp = tokio::time::timeout(opts.connect_timeout, open_sftp(&handle, name)) .await - .map_err(|e| remote(&e))?; - channel - .request_subsystem(true, "sftp") - .await - .map_err(|e| remote(&e))?; - let sftp = SftpSession::new(channel.into_stream()) - .await - .map_err(|e| remote(&e))?; + .map_err(|_| sftp_timeout(name))??; Ok(Arc::new(Conn { handle, sftp, @@ -239,6 +266,48 @@ async fn connect( })) } +fn sftp_timeout(name: &str) -> Error { + Error::Remote(format!("{name} didn't start file access (SFTP) in time")) +} + +/// Opens the `sftp` subsystem on a new channel. A server that only runs a fixed command for +/// the account (a forced command, as on code hosting servers) accepts the request and then +/// closes the channel without the SFTP greeting. +async fn open_sftp(handle: &Handle, name: &str) -> Result { + let refused = || Error::Remote(format!("{name} doesn't offer file access (SFTP)")); + let mut channel = handle + .channel_open_session() + .await + .map_err(|e| Error::Remote(why(&e, name)))?; + channel + .request_subsystem(true, "sftp") + .await + .map_err(|e| Error::Remote(why(&e, name)))?; + // russh doesn't wait for the reply: read it here, before the stream takes the channel. + loop { + match channel.wait().await { + Some(ChannelMsg::Success) => break, + Some( + ChannelMsg::Failure + | ChannelMsg::Eof + | ChannelMsg::Close + | ChannelMsg::ExitStatus { .. } + | ChannelMsg::ExitSignal { .. }, + ) + | None => return Err(refused()), + Some(_) => {} + } + } + SftpSession::new(channel.into_stream()) + .await + .map_err(|e| match e { + SftpError::Timeout => sftp_timeout(name), + _ => Error::Remote(format!( + "{name} doesn't offer file access (SFTP) to this account" + )), + }) +} + /// A russh failure in plain words. fn why(e: &russh::Error, host: &str) -> String { use std::io::ErrorKind::*; diff --git a/crates/tunal-net/tests/sftp.rs b/crates/tunal-net/tests/sftp.rs index eaa6dbb..a61ddff 100644 --- a/crates/tunal-net/tests/sftp.rs +++ b/crates/tunal-net/tests/sftp.rs @@ -59,6 +59,22 @@ fn blob(name: &str) -> String { struct Log { /// `password`, `publickey` and `none` attempts, in order. attempts: Mutex>, + /// TCP connections the server accepted. + connections: AtomicU32, + /// How the server answers the `sftp` subsystem request. + subsystem: Mutex, +} + +#[derive(Default, Clone, Copy)] +enum Subsystem { + #[default] + Serve, + /// Replies failure, as a server without SFTP does. + Refuse, + /// Replies success, then exits and closes the channel at once, as a forced command does. + ForcedCommand, + /// Closes the channel without a reply. + Close, } #[derive(Clone)] @@ -72,6 +88,7 @@ impl russh::server::Server for SshServer { type Handler = SshSession; fn new_client(&mut self, _: Option) -> SshSession { + self.log.connections.fetch_add(1, Ordering::Relaxed); SshSession { server: self.clone(), channels: Mutex::default(), @@ -147,9 +164,18 @@ impl russh::server::Handler for SshSession { name: &str, session: &mut Session, ) -> Result<(), Self::Error> { - if name != "sftp" { - session.channel_failure(channel_id)?; - return Ok(()); + let mode = *self.server.log.subsystem.lock().unwrap(); + match mode { + _ if name != "sftp" => return session.channel_failure(channel_id), + Subsystem::Serve => {} + Subsystem::Refuse => return session.channel_failure(channel_id), + Subsystem::ForcedCommand => { + session.channel_success(channel_id)?; + session.exit_status_request(channel_id, 1)?; + session.eof(channel_id)?; + return session.close(channel_id); + } + Subsystem::Close => return session.close(channel_id), } let channel = self.channels.lock().unwrap().remove(&channel_id).unwrap(); session.channel_success(channel_id)?; @@ -435,6 +461,8 @@ impl TapRoot for File { #[derive(Default)] struct Answers { host_key: Mutex>, + /// How long the user takes to answer the host key question. + host_key_delay: Mutex, password: Mutex>, passphrase: Mutex>, host_key_prompts: AtomicU32, @@ -447,6 +475,7 @@ struct Answers { impl Prompts for Answers { fn confirm_host_key(&self, info: &HostKeyInfo) -> HostKeyChoice { self.host_key_prompts.fetch_add(1, Ordering::Relaxed); + std::thread::sleep(*self.host_key_delay.lock().unwrap()); *self.seen_host_key.lock().unwrap() = Some(info.clone()); self.host_key .lock() @@ -732,7 +761,7 @@ fn wrong_key_is_denied_without_falling_back_to_a_password() { let Error::Remote(msg) = f.location.stat(&f.direct("/home")).unwrap_err() else { panic!() }; - assert!(msg.contains("authentication failed"), "{msg}"); + assert!(msg.contains("127.0.0.1 didn't accept the key"), "{msg}"); assert_eq!(f.answers.password_prompts.load(Ordering::Relaxed), 0); } @@ -756,7 +785,10 @@ fn wrong_password_gets_three_tries_then_fails() { let Error::Remote(msg) = f.location.stat(&f.direct("/home")).unwrap_err() else { panic!() }; - assert!(msg.contains("authentication failed"), "{msg}"); + assert!( + msg.contains("127.0.0.1 didn't accept the password"), + "{msg}" + ); assert_eq!(f.answers.password_prompts.load(Ordering::Relaxed), 3); assert_eq!(f.attempts().len(), 3); } @@ -795,11 +827,64 @@ fn wrong_passphrase_is_asked_up_to_three_times_and_nothing_is_offered() { *f.answers.passphrase.lock().unwrap() = Some("wrong".into()); f.location .set_auth("127.0.0.1", AuthPref::Key(fixture("k_enc"))); - assert!(f.location.stat(&f.direct("/home")).is_err()); + let Error::Remote(msg) = f.location.stat(&f.direct("/home")).unwrap_err() else { + panic!() + }; + assert_eq!(msg, "the key k_enc wasn't unlocked"); assert_eq!(f.answers.passphrase_prompts.load(Ordering::Relaxed), 3); assert!(f.attempts().is_empty()); } +// ---------------------------------------------------------------- servers without SFTP + +fn sftp_error(subsystem: Subsystem) -> (Fixture, String) { + let f = trusted(); + *f.log.subsystem.lock().unwrap() = subsystem; + let Error::Remote(msg) = f.location.stat(&f.uri("/home")).unwrap_err() else { + panic!() + }; + (f, msg) +} + +#[test] +fn a_refused_sftp_subsystem_says_so() { + let (_f, msg) = sftp_error(Subsystem::Refuse); + assert_eq!(msg, "box doesn't offer file access (SFTP)"); +} + +#[test] +// Regression: a git server's forced command closed the channel and "sender dropped" leaked. +fn a_forced_command_account_says_it_has_no_file_access() { + let (_f, msg) = sftp_error(Subsystem::ForcedCommand); + assert_eq!(msg, "box doesn't offer file access (SFTP) to this account"); +} + +#[test] +fn a_channel_closed_without_reply_says_so() { + let (_f, msg) = sftp_error(Subsystem::Close); + assert_eq!(msg, "box doesn't offer file access (SFTP)"); +} + +#[test] +// Regression: two requests at once (a double click) connected twice and showed two errors. +fn requests_at_once_share_one_connect_attempt() { + let f = Fixture::new(); + *f.answers.host_key.lock().unwrap() = Some(HostKeyChoice::Once); + *f.answers.host_key_delay.lock().unwrap() = std::time::Duration::from_millis(300); + *f.log.subsystem.lock().unwrap() = Subsystem::Refuse; + let errors: Vec = std::thread::scope(|s| { + let a = s.spawn(|| f.location.stat(&f.uri("/home")).unwrap_err()); + let b = s.spawn(|| f.location.stat(&f.uri("/home")).unwrap_err()); + vec![a.join().unwrap(), b.join().unwrap()] + }); + assert_eq!(errors[0], errors[1]); + assert_eq!(f.log.connections.load(Ordering::Relaxed), 1); + assert_eq!(f.answers.host_key_prompts.load(Ordering::Relaxed), 1); + // A later request tries again. + f.location.stat(&f.uri("/home")).unwrap_err(); + assert_eq!(f.log.connections.load(Ordering::Relaxed), 2); +} + #[test] fn refused_connection_and_proxy_hosts_give_plain_errors() { let f = trusted(); diff --git a/crates/tunal/src/net_bridge.rs b/crates/tunal/src/net_bridge.rs index 9eed7fa..908abb3 100644 --- a/crates/tunal/src/net_bridge.rs +++ b/crates/tunal/src/net_bridge.rs @@ -146,6 +146,9 @@ struct Net { editing: std::cell::Cell>, /// What the sidebar shows now, to skip identical updates. shown: RefCell>, + /// Entries whose home folder is being looked up: a second click (or a double click) + /// waits for that attempt instead of starting another. + opening: RefCell>, } thread_local! { @@ -316,6 +319,7 @@ pub fn attach(ui: &MainWindow, shell: &Rc, sftp: Arc) { show_ssh_hosts: std::cell::Cell::new(true), editing: std::cell::Cell::new(None), shown: RefCell::new(Vec::new()), + opening: RefCell::new(Vec::new()), }); NET.with(|n| *n.borrow_mut() = Some(net.clone())); @@ -624,6 +628,10 @@ impl Net { shell.open_at(uri, new_tab); return; } + if self.opening.borrow().contains(&uri) { + return; + } + self.opening.borrow_mut().push(uri.clone()); let sftp = self.sftp.clone(); let ui = self.ui.clone(); std::thread::spawn(move || { @@ -632,6 +640,7 @@ impl Net { let Some(net) = net() else { return; }; + net.opening.borrow_mut().retain(|u| *u != uri); if let Some(shell) = net.shell.upgrade() { match home { Ok(home) => shell.open_at(home, new_tab),