Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

security: require explicit mobile SSH host key approval

RoversX22494d670ec3
diff --git a/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt b/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt
index 99f29d2c..74b67ab5 100644
--- a/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt
+++ b/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt
@@ -19,6 +19,7 @@ import androidx.compose.ui.graphics.Color
import com.roversx.thinkterm.core.Core
import com.roversx.thinkterm.core.Notify
import java.util.concurrent.atomic.AtomicBoolean
+import java.util.UUID
/// The shell's side of the thread contract. `Notify` calls arrive on the
/// core thread; nothing here blocks them and nothing here calls back into
@@ -37,6 +38,12 @@ class TerminalModel(
/// The host this screen shows; edited in place from the failure card.
var host by mutableStateOf(host)
+ data class HostKeyChallenge(val requestId: String, val endpoint: Host, val fingerprint: String)
+ var pendingHostKey by mutableStateOf<HostKeyChallenge?>(null)
+ private set
+ private var activeRequestId: String? = null
+ private var requestedHost: Host? = null
+
// The App's views, refreshed when the core says something changed.
var tabs by mutableStateOf<TabsView?>(null)
@@ -237,6 +244,10 @@ class TerminalModel(
}
fun connect() {
+ clearHostKeyRequest()
+ val requestId = UUID.randomUUID().toString()
+ activeRequestId = requestId
+ requestedHost = host
restoredThread = false
connected = true
val h = host
@@ -244,6 +255,7 @@ class TerminalModel(
val passphrase = if (h.id == Host.PROBE_ID) null else store.passphrase(h.id)
log("shell: connecting ${h.address}, ${secret.length} chars of secret")
core.connect(
+ requestId = requestId,
host = h.hostname,
port = h.port.coerceIn(1, 65535).toUShort(),
user = h.user,
@@ -269,15 +281,31 @@ class TerminalModel(
}
fun disconnect() {
+ clearHostKeyRequest()
connected = false
core.disconnect()
}
+ private fun clearHostKeyRequest() {
+ activeRequestId = null
+ requestedHost = null
+ pendingHostKey = null
+ }
+
+ fun approveHostKey(challenge: HostKeyChallenge) {
+ if (activeRequestId != challenge.requestId || requestedHost != challenge.endpoint ||
+ host != challenge.endpoint || host.knownHost != null) return
+ if (host.id != Host.PROBE_ID) store.rememberHostKey(host.id, challenge.fingerprint)
+ host = host.copy(knownHost = challenge.fingerprint)
+ connect()
+ }
+
val isConnected: Boolean
get() = connection.isNotEmpty() && !connection.startsWith("disconnected") && !connection.startsWith("failed")
/// Leaving the screen for good: the frame loop stops, then the core.
fun shutdown() {
+ clearHostKeyRequest()
running = false
choreographer.removeFrameCallback(tick)
main.removeCallbacks(statsTick)
@@ -555,10 +583,12 @@ class TerminalModel(
}
}
- override fun onHostKey(fingerprint: String) {
+ override fun onHostKeyRequired(requestId: String, fingerprint: String) {
main.post {
- log("host key $fingerprint")
- if (host.id != Host.PROBE_ID) store.rememberHostKey(host.id, fingerprint)
+ val endpoint = requestedHost
+ if (requestId == activeRequestId && endpoint != null && host == endpoint && host.knownHost == null) {
+ pendingHostKey = HostKeyChallenge(requestId, endpoint, fingerprint)
+ }
}
}
diff --git a/android/app/src/main/java/com/roversx/thinkterm/TerminalScreen.kt b/android/app/src/main/java/com/roversx/thinkterm/TerminalScreen.kt
index 475bf991..a79a05af 100644
--- a/android/app/src/main/java/com/roversx/thinkterm/TerminalScreen.kt
+++ b/android/app/src/main/java/com/roversx/thinkterm/TerminalScreen.kt
@@ -786,6 +786,23 @@ private fun BoxScope.TerminalOverlays(model: TerminalModel, showLog: Boolean, on
.padding(6.dp),
)
}
+ model.pendingHostKey?.let { challenge ->
+ androidx.compose.material3.AlertDialog(
+ onDismissRequest = { model.disconnect() },
+ title = { Text(tr("hostkey.approve.title")) },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(16.dp), modifier = Modifier.verticalScroll(rememberScrollState())) {
+ Text("${challenge.endpoint.hostname}:${challenge.endpoint.port}")
+ androidx.compose.foundation.text.selection.SelectionContainer {
+ Text(challenge.fingerprint, fontFamily = FontFamily.Monospace)
+ }
+ Text(tr("hostkey.approve.body"))
+ }
+ },
+ confirmButton = { TextButton(onClick = { model.approveHostKey(challenge) }) { Text(tr("hostkey.approve.accept")) } },
+ dismissButton = { TextButton(onClick = { model.disconnect() }) { Text(tr("cancel")) } },
+ )
+ }
val phase = ConnectionPhase.of(model.connection)
if (model.reconnecting && !settings.autoReconnect && phase == null) {
// Asked not to redial: the card offers it instead.
diff --git a/ios/Resources/strings.json b/ios/Resources/strings.json
index 09d5bfed..7a96935a 100644
--- a/ios/Resources/strings.json
+++ b/ios/Resources/strings.json
@@ -206,7 +206,10 @@
"version": "Version",
"window.n": "Fenster %d",
"workspaces": "Workspaces",
- "zoom": "Bereich zoomen"
+ "zoom": "Bereich zoomen",
+ "hostkey.approve.title": "Diesem SSH-Hostschlüssel vertrauen?",
+ "hostkey.approve.body": "Bevor Sie ein Passwort senden oder sich mit einem Schlüssel authentifizieren, gleichen Sie diesen SHA-256-Fingerabdruck über einen vertrauenswürdigen Kanal mit dem Serveradministrator ab. Brechen Sie bei einer Abweichung ab.",
+ "hostkey.approve.accept": "Vertrauen und verbinden"
},
"en-US": {
"archived": "Archived",
@@ -415,7 +418,10 @@
"version": "Version",
"window.n": "Window %d",
"workspaces": "Workspaces",
- "zoom": "Zoom pane"
+ "zoom": "Zoom pane",
+ "hostkey.approve.title": "Trust this SSH host key?",
+ "hostkey.approve.body": "Before sending a password or authenticating with a key, verify this SHA-256 fingerprint with the server administrator over a trusted channel. Cancel if it differs.",
+ "hostkey.approve.accept": "Trust and connect"
},
"fr-FR": {
"archived": "Archivés",
@@ -624,7 +630,10 @@
"version": "Version",
"window.n": "Fenêtre %d",
"workspaces": "Espaces de travail",
- "zoom": "Zoomer le volet"
+ "zoom": "Zoomer le volet",
+ "hostkey.approve.title": "Faire confiance à cette clé d’hôte SSH ?",
+ "hostkey.approve.body": "Avant d’envoyer un mot de passe ou de vous authentifier avec une clé, vérifiez cette empreinte SHA-256 auprès de l’administrateur du serveur via un canal de confiance. Annulez si elle ne correspond pas.",
+ "hostkey.approve.accept": "Faire confiance et se connecter"
},
"ja-JP": {
"archived": "アーカイブ済み",
@@ -833,7 +842,10 @@
"version": "バージョン",
"window.n": "ウインドウ %d",
"workspaces": "ワークスペース",
- "zoom": "ペインをズーム"
+ "zoom": "ペインをズーム",
+ "hostkey.approve.title": "この SSH ホスト鍵を信頼しますか?",
+ "hostkey.approve.body": "パスワードを送信したり鍵で認証したりする前に、信頼できる通信手段でサーバー管理者にこの SHA-256 フィンガープリントを確認してください。一致しない場合はキャンセルしてください。",
+ "hostkey.approve.accept": "信頼して接続"
},
"zh-CN": {
"archived": "已归档",
@@ -1042,6 +1054,9 @@
"version": "版本",
"window.n": "窗口 %d",
"workspaces": "工作区",
- "zoom": "缩放 pane"
+ "zoom": "缩放 pane",
+ "hostkey.approve.title": "信任这个 SSH 主机密钥?",
+ "hostkey.approve.body": "发送密码或进行密钥认证前,请通过可信渠道与服务器管理员核对以上 SHA-256 指纹。不一致请取消。",
+ "hostkey.approve.accept": "信任并连接"
}
}
diff --git a/ios/Sources/TerminalModel.swift b/ios/Sources/TerminalModel.swift
index 6b5e7834..292d7d94 100644
--- a/ios/Sources/TerminalModel.swift
+++ b/ios/Sources/TerminalModel.swift
@@ -77,6 +77,17 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
let core: Core
/// The host this screen shows; edited in place from the failure card.
@Published var host: Host?
+ struct HostKeyChallenge: Identifiable {
+ let id: String
+ let hostname: String
+ let port: Int
+ let hostID: UUID?
+ let fingerprint: String
+ }
+ @Published var pendingHostKey: HostKeyChallenge?
+ private var activeRequestID: String?
+ private var requestedEndpoint: (hostname: String, port: Int, hostID: UUID?)?
+
weak var store: HostStore?
weak var inputView: TerminalInputView?
var cursorRect = CGRect(x: 8, y: 8, width: 2, height: 20)
@@ -159,6 +170,7 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
func enterScreen() { displayLink?.isPaused = false }
func shutdown() {
+ clearHostKeyRequest()
displayLink?.invalidate()
statsTimer?.invalidate()
detach()
@@ -207,17 +219,22 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
func connectProbe() {
connect(
hostname: "127.0.0.1", port: 2299, user: probeUser, authKind: "key-path",
- secret: probeKeyPath, passphrase: nil, knownHost: nil, remoteCommand: probeRemoteCommand
+ secret: probeKeyPath, passphrase: nil, knownHost: hostKeyToRemember, remoteCommand: probeRemoteCommand
)
}
private func connect(hostname: String, port: Int, user: String, authKind: String, secret: String, passphrase: String?, knownHost: String?, remoteCommand: String) {
+ clearHostKeyRequest()
+ let requestID = UUID().uuidString
+ activeRequestID = requestID
+ requestedEndpoint = (hostname, port, host?.id)
let paths = fontPaths
guard paths.count == 2 else {
log("shell: fonts missing from the bundle (\(paths))")
return
}
core.connect(
+ requestId: requestID,
host: hostname, port: UInt16(clamping: port), user: user,
authKind: authKind, secret: secret, passphrase: passphrase, knownHost: knownHost,
remoteCommand: remoteCommand, deviceId: Self.deviceId, keepaliveSecs: UInt32(max(settings.keepAliveSeconds, 0)),
@@ -226,7 +243,31 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
)
}
- func disconnect() { core.disconnect() }
+ private func clearHostKeyRequest() {
+ activeRequestID = nil
+ requestedEndpoint = nil
+ pendingHostKey = nil
+ }
+
+ func disconnect() { clearHostKeyRequest(); core.disconnect() }
+
+ func approveHostKey(_ challenge: HostKeyChallenge) {
+ guard activeRequestID == challenge.id,
+ requestedEndpoint?.hostname == challenge.hostname,
+ requestedEndpoint?.port == challenge.port,
+ host?.id == challenge.hostID else { return }
+ if var host = host {
+ guard host.hostname == challenge.hostname, host.port == challenge.port,
+ host.knownHost == nil else { return }
+ host.knownHost = challenge.fingerprint
+ store?.rememberHostKey(challenge.fingerprint, for: host.id)
+ self.host = host
+ } else {
+ hostKeyToRemember = challenge.fingerprint
+ }
+ connect()
+ }
+
// MARK: input
@@ -610,12 +651,16 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
}
}
- fileprivate func coreHostKey(_ fingerprint: String) {
+ fileprivate func coreHostKeyRequired(_ requestID: String, _ fingerprint: String) {
DispatchQueue.main.async {
- self.log("host key " + fingerprint)
+ guard self.activeRequestID == requestID, let endpoint = self.requestedEndpoint,
+ self.host?.id == endpoint.hostID else { return }
if let host = self.host {
- self.store?.rememberHostKey(fingerprint, for: host.id)
+ guard host.hostname == endpoint.hostname, host.port == endpoint.port,
+ host.knownHost == nil else { return }
}
+ self.pendingHostKey = HostKeyChallenge(id: requestID, hostname: endpoint.hostname,
+ port: endpoint.port, hostID: endpoint.hostID, fingerprint: fingerprint)
}
}
@@ -905,7 +950,7 @@ private final class NotifySink: Notify, @unchecked Sendable {
self.model?.cursorRect = CGRect(x: left, y: top, width: width, height: height)
}
}
- func onHostKey(fingerprint: String) { model?.coreHostKey(fingerprint) }
+ func onHostKeyRequired(requestId: String, fingerprint: String) { model?.coreHostKeyRequired(requestId, fingerprint) }
func onPublished(key: String, value: String) { model?.corePublished(key, value) }
func onBell() { model?.coreBell() }
func onPreview(pane: UInt32, rows: String) {
diff --git a/ios/Sources/TerminalScreen.swift b/ios/Sources/TerminalScreen.swift
index e2770238..a83a5536 100644
--- a/ios/Sources/TerminalScreen.swift
+++ b/ios/Sources/TerminalScreen.swift
@@ -170,6 +170,22 @@ struct TerminalScreen: View {
}
}
.ignoresSafeArea(.container, edges: .bottom)
+ .sheet(item: $model.pendingHostKey) { challenge in
+ ScrollView {
+ VStack(alignment: .leading, spacing: 20) {
+ Text(tr("hostkey.approve.title")).font(.headline)
+ Text("\(challenge.hostname):\(challenge.port)")
+ Text(challenge.fingerprint).font(.system(.body, design: .monospaced))
+ .textSelection(.enabled).fixedSize(horizontal: false, vertical: true)
+ Text(tr("hostkey.approve.body"))
+ HStack {
+ Button(tr("cancel"), role: .cancel) { model.disconnect() }
+ Spacer()
+ Button(tr("hostkey.approve.accept")) { model.approveHostKey(challenge) }
+ }
+ }.padding(24)
+ }.presentationDetents([.medium, .large])
+ }
.sheet(isPresented: $showSettings) {
NavigationStack {
SettingsView(model: model, showLog: $showLog)
diff --git a/ios/tools/gen-strings.py b/ios/tools/gen-strings.py
index f1c50c8d..c2441ed9 100644
--- a/ios/tools/gen-strings.py
+++ b/ios/tools/gen-strings.py
@@ -147,6 +147,27 @@ EXTRA = {
"Leer führt auf dem Host `thinkterm cli --prefer-mux proxy` aus.",
],
"f.hostkey": ["Host key", "主机密钥", "ホスト鍵", "Clé de l’hôte", "Hostschlüssel"],
+ "hostkey.approve.title": [
+ "Trust this SSH host key?",
+ "信任这个 SSH 主机密钥?",
+ "この SSH ホスト鍵を信頼しますか?",
+ "Faire confiance à cette clé d’hôte SSH ?",
+ "Diesem SSH-Hostschlüssel vertrauen?",
+ ],
+ "hostkey.approve.body": [
+ "Before sending a password or authenticating with a key, verify this SHA-256 fingerprint with the server administrator over a trusted channel. Cancel if it differs.",
+ "发送密码或进行密钥认证前,请通过可信渠道与服务器管理员核对以上 SHA-256 指纹。不一致请取消。",
+ "パスワードを送信したり鍵で認証したりする前に、信頼できる通信手段でサーバー管理者にこの SHA-256 フィンガープリントを確認してください。一致しない場合はキャンセルしてください。",
+ "Avant d’envoyer un mot de passe ou de vous authentifier avec une clé, vérifiez cette empreinte SHA-256 auprès de l’administrateur du serveur via un canal de confiance. Annulez si elle ne correspond pas.",
+ "Bevor Sie ein Passwort senden oder sich mit einem Schlüssel authentifizieren, gleichen Sie diesen SHA-256-Fingerabdruck über einen vertrauenswürdigen Kanal mit dem Serveradministrator ab. Brechen Sie bei einer Abweichung ab.",
+ ],
+ "hostkey.approve.accept": [
+ "Trust and connect",
+ "信任并连接",
+ "信頼して接続",
+ "Faire confiance et se connecter",
+ "Vertrauen und verbinden",
+ ],
# settings
"cursor.auto": [
"As the program sets",
diff --git a/thinkterm-mobile/src/core.rs b/thinkterm-mobile/src/core.rs
index a514d450..448f2061 100644
--- a/thinkterm-mobile/src/core.rs
+++ b/thinkterm-mobile/src/core.rs
@@ -777,7 +777,10 @@ impl State {
link.closed(format!("{err:#}"));
}
}
- Net::HostKey(fingerprint) => self.notify.on_host_key(fingerprint),
+ Net::HostKeyRequired {
+ request_id,
+ fingerprint,
+ } => self.notify.on_host_key_required(request_id, fingerprint),
Net::Stderr(text) => self.notify.on_log(format!("remote: {}", text.trim_end())),
Net::Exit(code) => self
.notify
@@ -1279,7 +1282,7 @@ mod tests {
fn on_clipboard(&self, _: String) {}
fn on_focus_input(&self) {}
fn on_ime_anchor(&self, _: f64, _: f64, _: f64, _: f64) {}
- fn on_host_key(&self, _: String) {}
+ fn on_host_key_required(&self, _: String, _: String) {}
fn on_published(&self, _: String, _: String) {}
fn on_bell(&self) {}
fn on_preview(&self, _: u32, _: String) {}
diff --git a/thinkterm-mobile/src/lib.rs b/thinkterm-mobile/src/lib.rs
index baa38a6d..6a526dc6 100644
--- a/thinkterm-mobile/src/lib.rs
+++ b/thinkterm-mobile/src/lib.rs
@@ -48,9 +48,8 @@ pub trait Notify: Send + Sync {
fn on_focus_input(&self);
/// Where the cursor cell is, in points, in the terminal view.
fn on_ime_anchor(&self, left: f64, top: f64, width: f64, height: f64);
- /// The host's key fingerprint, seen before authentication: the shell
- /// remembers it and passes it back as `known_host` next time.
- fn on_host_key(&self, fingerprint: String);
+ /// Authentication is blocked until the user approves this request's key.
+ fn on_host_key_required(&self, request_id: String, fingerprint: String);
/// Something the App publishes for the display layer, keyed: "bg" is
/// the terminal's background as a hex colour, for the chrome around it.
fn on_published(&self, key: String, value: String);
@@ -285,6 +284,7 @@ impl Core {
#[allow(clippy::too_many_arguments)]
pub fn connect(
&self,
+ request_id: String,
host: String,
port: u16,
user: String,
@@ -310,6 +310,7 @@ impl Core {
let _ = self.tx.send(core::Cmd::Connect {
params: core::ConnectParams {
ssh: ssh::SshParams {
+ request_id,
host,
port,
user,
diff --git a/thinkterm-mobile/src/link.rs b/thinkterm-mobile/src/link.rs
index 5ca9ab12..2d407eb2 100644
--- a/thinkterm-mobile/src/link.rs
+++ b/thinkterm-mobile/src/link.rs
@@ -33,6 +33,7 @@ pub struct SshLink(Rc<Inner>);
pub(crate) fn test_link() -> SshLink {
SshLink::new(
SshParams {
+ request_id: "test".into(),
host: "unused".into(),
port: 22,
user: "test".into(),
diff --git a/thinkterm-mobile/src/ssh.rs b/thinkterm-mobile/src/ssh.rs
index ad9b9390..f12dd3c6 100644
--- a/thinkterm-mobile/src/ssh.rs
+++ b/thinkterm-mobile/src/ssh.rs
@@ -6,9 +6,9 @@
//! stderr, the exit status, the close -- is delivered to the core thread
//! through the callback it gave us, which must not block.
//!
-//! The host key is trusted on first use: its fingerprint is reported so
-//! the shell can remember it, and a remembered one that no longer matches
-//! ends the dial before any authentication.
+//! An unknown host key ends the transport before authentication. The shell
+//! asks for explicit approval and retries with that exact fingerprint pinned.
+//! A remembered key that changes is always rejected.
use anyhow::{anyhow, Context, Result};
use russh::client::{self, Handler};
@@ -32,6 +32,7 @@ pub enum Auth {
#[derive(Debug, Clone)]
pub struct SshParams {
+ pub request_id: String,
pub host: String,
pub port: u16,
pub user: String,
@@ -51,8 +52,11 @@ pub enum Out {
#[derive(Debug)]
pub enum Net {
- /// The host's key fingerprint, before authentication.
- HostKey(String),
+ /// Transport stopped before authentication; only explicit approval may retry.
+ HostKeyRequired {
+ request_id: String,
+ fingerprint: String,
+ },
Connected,
Data(Vec<u8>),
Stderr(String),
@@ -81,7 +85,8 @@ impl Handler for HostKeyCheck {
Some(known) if known != &fingerprint => Err(anyhow!(
"the host's key changed: expected {known}, got {fingerprint}. If the host was reinstalled, forget it and add it again"
)),
- _ => Ok(true),
+ Some(_) => Ok(true),
+ None => Err(anyhow!("host key approval required before authentication")),
}
}
}
@@ -217,12 +222,15 @@ async fn run(
)
.await
.context("connecting timed out")?;
- let mut session = dial.context("ssh transport")?;
- // Only a key the check let through is worth remembering: the shells
- // pin whatever arrives here, and a mismatch must not replace the pin.
- if let Some(fingerprint) = seen.lock().unwrap().clone() {
- deliver(Net::HostKey(fingerprint));
+ if dial.is_err() && params.known_host.is_none() {
+ if let Some(fingerprint) = seen.lock().unwrap().clone() {
+ deliver(Net::HostKeyRequired {
+ request_id: params.request_id.clone(),
+ fingerprint,
+ });
+ }
}
+ let mut session = dial.context("ssh transport")?;
let auth = match &params.auth {
Auth::KeyPath(path) => {
@@ -334,3 +342,100 @@ async fn run(
}
}
}
+
+#[cfg(test)]
+mod host_key_tests {
+ use super::*;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ struct PasswordServer(Arc<AtomicUsize>);
+ impl russh::server::Handler for PasswordServer {
+ type Error = anyhow::Error;
+ async fn auth_password(&mut self, _: &str, password: &str) -> Result<russh::server::Auth> {
+ assert_eq!(password, "test-secret");
+ self.0.fetch_add(1, Ordering::SeqCst);
+ Ok(russh::server::Auth::Accept)
+ }
+ }
+
+ #[tokio::test]
+ async fn unknown_and_changed_keys_never_receive_credentials() {
+ let key = russh::keys::PrivateKey::random(
+ &mut crate::SysRng(ring::rand::SystemRandom::new()),
+ russh::keys::Algorithm::Ed25519,
+ )
+ .unwrap();
+ let fingerprint = key.public_key().fingerprint(HashAlg::Sha256).to_string();
+ let config = Arc::new(russh::server::Config {
+ keys: vec![key],
+ auth_rejection_time: Duration::ZERO,
+ auth_rejection_time_initial: Some(Duration::ZERO),
+ ..Default::default()
+ });
+ // The same real SSH transport is exercised with no pin, a mismatched
+ // pin and the explicitly approved pin. No UI or transport mock.
+ for (known_host, expected_auth, expected_challenge) in [
+ (None, 0, true),
+ (Some("SHA256:wrong".to_string()), 0, false),
+ (Some(fingerprint.clone()), 1, false),
+ ] {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let count = Arc::new(AtomicUsize::new(0));
+ let server_count = count.clone();
+ let server_config = config.clone();
+ let server = tokio::spawn(async move {
+ let (stream, _) = listener.accept().await.unwrap();
+ if let Ok(session) =
+ russh::server::run_stream(server_config, stream, PasswordServer(server_count))
+ .await
+ {
+ let _ = session.await;
+ }
+ });
+ let (_sender, receiver) = unbounded_channel();
+ let events = std::cell::RefCell::new(Vec::new());
+ let params = SshParams {
+ request_id: "attempt-42".into(),
+ host: "127.0.0.1".into(),
+ port,
+ user: "test".into(),
+ auth: Auth::Password("test-secret".into()),
+ known_host,
+ remote_command: "test".into(),
+ keepalive_secs: 0,
+ };
+ // The server intentionally refuses opening a session after auth.
+ let result = tokio::time::timeout(
+ Duration::from_secs(3),
+ run(params, receiver, &|event| events.borrow_mut().push(event)),
+ )
+ .await;
+ assert!(result
+ .expect("transport completes within the test deadline")
+ .is_err());
+ assert_eq!(count.load(Ordering::SeqCst), expected_auth);
+ let challenges: Vec<_> = events
+ .borrow()
+ .iter()
+ .filter_map(|event| match event {
+ Net::HostKeyRequired {
+ request_id,
+ fingerprint,
+ } => Some((request_id.clone(), fingerprint.clone())),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(
+ challenges,
+ if expected_challenge {
+ vec![("attempt-42".into(), fingerprint.clone())]
+ } else {
+ vec![]
+ }
+ );
+ server.abort();
+ let _ = server.await;
+ }
+ }
+}