S028: SFTP location with auth chain, host key checks and connection pool

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-19 00:05:26 -06:00
commit b36fea1436
11 changed files with 2076 additions and 32 deletions

1078
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -35,4 +35,8 @@ hmac = "0.13"
sha1 = "0.11"
futures-lite = "2"
idevice = { version = "0.1.68", default-features = false, features = ["ring", "usbmuxd", "afc", "pair"] }
tokio = { version = "1", features = ["rt-multi-thread", "net", "time"] }
tokio = { version = "1", features = ["rt-multi-thread", "net", "time", "sync"] }
russh = { version = "0.65", default-features = false, features = ["ring", "flate2", "rsa"] }
russh-sftp = "3"
secrecy = "0.10"
zeroize = "1"

View file

@ -10,13 +10,13 @@
docs/DECISIONS.md D-019, D-020; CLAUDE.md §3 (secrets); crates/tunal-core trait; russh/russh-sftp docs in ~/.cargo/registry.
## Steps
- [ ] Own tokio runtime on a background thread inside `tunal-net`; blocking `Location` API on top; russh crypto features on ring (D-019), not aws-lc-rs.
- [ ] Connection manager per (user, host, port): reuse, keepalive, reconnect, idle close.
- [ ] Auth chain: agent (`SSH_AUTH_SOCK`) → identity files (passphrase callback) → password / keyboard-interactive callback; secrets in `secrecy`/`zeroize` types only.
- [ ] Host key via known_hosts: Unknown → callback (SHA256 fingerprint), Mismatch → hard error.
- [ ] Location ops: readdir, stat/lstat, readlink, pipelined read/write, mkdir, rename (posix-rename extension when offered), delete; trash Unsupported (permanent delete with confirm).
- [ ] Example `--example sftp-ls -- <uri>` (only against a server the user names; otherwise build-only).
- [ ] PROGRESS entry, INDEX line, commit `S028: …`
- [x] Own tokio runtime on a background thread inside `tunal-net`; blocking `Location` API on top; russh crypto features on ring (D-019), not aws-lc-rs.
- [x] Connection manager per (user, host, port): reuse, keepalive, reconnect, idle close.
- [x] Auth chain: agent (`SSH_AUTH_SOCK`) → identity files (passphrase callback) → password / keyboard-interactive callback; secrets in `secrecy`/`zeroize` types only.
- [x] Host key via known_hosts: Unknown → callback (SHA256 fingerprint), Mismatch → hard error.
- [x] Location ops: readdir, stat/lstat, readlink, pipelined read/write, mkdir, rename (posix-rename extension when offered), delete; trash Unsupported (permanent delete with confirm).
- [x] Example `--example sftp-ls -- <uri>` (only against a server the user names; otherwise build-only).
- [x] PROGRESS entry, INDEX line, commit `S028: …`
## End criteria
- `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass.

View file

@ -62,7 +62,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v
## 10 Network
- [x] [S027 — ssh config and known_hosts](10%20Network/S027-ssh-config-known-hosts.md) · Sonnet high
- [ ] [S028 — SFTP location](10%20Network/S028-sftp-location.md) · Opus high
- [x] [S028 — SFTP location](10%20Network/S028-sftp-location.md) · Opus high
- [ ] [S029 — SFTP connections in the UI](10%20Network/S029-sftp-ui.md) · Opus high
## 11 Native drag and drop

View file

@ -9,3 +9,9 @@ publish.workspace = true
base64.workspace = true
hmac.workspace = true
sha1.workspace = true
tunal-core = { path = "../tunal-core" }
tokio.workspace = true
russh.workspace = true
russh-sftp.workspace = true
secrecy.workspace = true
zeroize.workspace = true

View file

@ -0,0 +1,72 @@
//! `cargo run -p tunal-net --example sftp-ls -- sftp://[user@]host[:port]/path`
//! Lists a remote folder. Only run it against a server you name; asks on the terminal.
use std::io::{self, BufRead, Write};
use std::path::Path;
use std::sync::Arc;
use secrecy::SecretString;
use tunal_core::{Location, Uri};
use tunal_net::auth::{HostKeyInfo, InteractiveRequest, Prompts};
use tunal_net::sftp::SftpLocation;
struct Terminal;
fn line(prompt: &str, hidden: bool) -> Option<SecretString> {
eprint!("{prompt} ");
let _ = io::stderr().flush();
if hidden {
let _ = std::process::Command::new("stty").arg("-echo").status();
}
let mut s = String::new();
let ok = io::stdin().lock().read_line(&mut s).is_ok_and(|n| n > 0);
if hidden {
let _ = std::process::Command::new("stty").arg("echo").status();
eprintln!();
}
ok.then(|| SecretString::from(s.trim_end().to_owned()))
}
impl Prompts for Terminal {
fn confirm_host_key(&self, i: &HostKeyInfo) -> bool {
use secrecy::ExposeSecret;
let q = format!(
"Unknown host {}:{} {} {}. Accept? [y/N]",
i.host, i.port, i.key_type, i.fingerprint
);
line(&q, false).is_some_and(|a| a.expose_secret().eq_ignore_ascii_case("y"))
}
fn password(&self, user: &str, host: &str) -> Option<SecretString> {
line(&format!("Password for {user}@{host}:"), true)
}
fn passphrase(&self, key: &Path) -> Option<SecretString> {
line(&format!("Passphrase for {}:", key.display()), true)
}
fn interactive(&self, req: &InteractiveRequest) -> Option<Vec<SecretString>> {
req.prompts.iter().map(|p| line(&p.text, !p.echo)).collect()
}
}
fn main() {
let arg = std::env::args()
.nth(1)
.expect("usage: sftp-ls sftp://[user@]host[:port]/path");
let uri = Uri::parse(&arg).expect("not a URI");
let sftp = SftpLocation::new(Arc::new(Terminal));
let result = sftp.list(&uri, &mut |entries| {
for e in entries {
println!(
"{:>10} {:o} {} {:?}",
e.size, e.mode, e.display_name, e.kind
);
}
std::ops::ControlFlow::Continue(())
});
if let Err(e) = result {
eprintln!("error: {e}");
std::process::exit(1);
}
}

View file

@ -0,0 +1,274 @@
//! Authentication chain (agent, identity files, password / keyboard-interactive) and the
//! prompt callbacks the UI implements. Secrets live in `secrecy` types and are never logged.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use russh::MethodKind;
use russh::client::{Handle, Handler, KeyboardInteractiveAuthResponse};
use russh::keys::agent::AgentIdentity;
use russh::keys::agent::client::AgentClient;
use russh::keys::{self, HashAlg, PrivateKeyWithHashAlg};
use secrecy::{ExposeSecret, SecretString};
use tunal_core::Error;
use crate::ssh_config::{Resolved, ssh_dir};
const MAX_TRIES: usize = 3;
/// A host key not seen before, shown to the user to accept or refuse.
#[derive(Debug, Clone)]
pub struct HostKeyInfo {
pub host: String,
pub port: u16,
/// e.g. `ssh-ed25519`.
pub key_type: String,
/// `SHA256:…`, as `ssh-keygen -l` prints it.
pub fingerprint: String,
}
/// One keyboard-interactive question.
#[derive(Debug, Clone)]
pub struct InteractivePrompt {
pub text: String,
/// False for secrets: the answer must not be shown while typing.
pub echo: bool,
}
/// A keyboard-interactive round.
#[derive(Debug, Clone)]
pub struct InteractiveRequest {
pub name: String,
pub instructions: String,
pub prompts: Vec<InteractivePrompt>,
}
/// Questions the connection layer asks the user. Called on a worker thread and may block
/// until the user answers; `None` / `false` means the user cancelled. Defaults refuse.
pub trait Prompts: Send + Sync {
/// Unknown host key: accept (and remember in Tunal's known_hosts) or refuse.
fn confirm_host_key(&self, _info: &HostKeyInfo) -> bool {
false
}
/// Account password for `user@host`.
fn password(&self, _user: &str, _host: &str) -> Option<SecretString> {
None
}
/// Passphrase for the encrypted private key file `key`.
fn passphrase(&self, _key: &Path) -> Option<SecretString> {
None
}
/// Answers for a keyboard-interactive round, one per prompt.
fn interactive(&self, _req: &InteractiveRequest) -> Option<Vec<SecretString>> {
None
}
}
/// Refuses every question: only agent and unencrypted keys work.
pub struct NoPrompts;
impl Prompts for NoPrompts {}
/// Runs a blocking prompt callback off the async worker.
async fn ask<T: Send + 'static>(
prompts: &Arc<dyn Prompts>,
f: impl FnOnce(&dyn Prompts) -> T + Send + 'static,
) -> Option<T> {
let prompts = prompts.clone();
tokio::task::spawn_blocking(move || f(&*prompts)).await.ok()
}
pub(crate) async fn authenticate<H: Handler>(
handle: &mut Handle<H>,
user: &str,
host: &str,
resolved: &Resolved,
prompts: &Arc<dyn Prompts>,
) -> Result<(), Error> {
let files = identity_files(resolved);
let rsa_hash = handle
.best_supported_rsa_hash()
.await
.ok()
.flatten()
.flatten();
if try_agent(handle, user, resolved, &files, rsa_hash).await {
return Ok(());
}
for file in &files {
if try_key_file(handle, user, file, rsa_hash, prompts).await {
return Ok(());
}
}
let methods = match handle.authenticate_none(user).await {
Ok(result) if result.success() => return Ok(()),
Ok(russh::client::AuthResult::Failure {
remaining_methods, ..
}) => remaining_methods,
_ => return Err(denied()),
};
if methods.contains(&MethodKind::Password) {
for _ in 0..MAX_TRIES {
let (u, h) = (user.to_owned(), host.to_owned());
let Some(Some(password)) = ask(prompts, move |p| p.password(&u, &h)).await else {
break;
};
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())),
}
}
}
if methods.contains(&MethodKind::KeyboardInteractive)
&& try_interactive(handle, user, prompts).await
{
return Ok(());
}
Err(denied())
}
fn denied() -> Error {
Error::Remote("authentication failed".into())
}
/// Identity files to try: the configured ones, else the usual defaults that exist.
fn identity_files(resolved: &Resolved) -> Vec<PathBuf> {
if !resolved.identity_files.is_empty() {
return resolved
.identity_files
.iter()
.filter(|f| f.is_file())
.cloned()
.collect();
}
let Some(dir) = ssh_dir() else {
return Vec::new();
};
["id_ed25519", "id_ecdsa", "id_rsa"]
.iter()
.map(|n| dir.join(n))
.filter(|f| f.is_file())
.collect()
}
/// Agent keys; with `IdentitiesOnly` only those matching a `<identity>.pub` file.
async fn try_agent<H: Handler>(
handle: &mut Handle<H>,
user: &str,
resolved: &Resolved,
files: &[PathBuf],
rsa_hash: Option<HashAlg>,
) -> bool {
let Ok(mut agent) = AgentClient::connect_env().await else {
return false;
};
let Ok(identities) = agent.request_identities().await else {
return false;
};
let allowed: Vec<_> = files
.iter()
.filter_map(|f| keys::load_public_key(f.with_extension("pub")).ok())
.map(|k| k.fingerprint(HashAlg::Sha256))
.collect();
for identity in identities {
let AgentIdentity::PublicKey { key, .. } = identity else {
continue;
};
if resolved.identities_only && !allowed.contains(&key.fingerprint(HashAlg::Sha256)) {
continue;
}
let hash = key.algorithm().is_rsa().then_some(rsa_hash).flatten();
if let Ok(r) = handle
.authenticate_publickey_with(user, key, hash, &mut agent)
.await
&& r.success()
{
return true;
}
}
false
}
async fn try_key_file<H: Handler>(
handle: &mut Handle<H>,
user: &str,
file: &Path,
rsa_hash: Option<HashAlg>,
prompts: &Arc<dyn Prompts>,
) -> bool {
let mut key = keys::load_secret_key(file, None);
for _ in 0..MAX_TRIES {
if !matches!(key, Err(keys::Error::KeyIsEncrypted)) {
break;
}
let path = file.to_path_buf();
let Some(Some(pass)) = ask(prompts, move |p| p.passphrase(&path)).await else {
return false;
};
key = keys::load_secret_key(file, Some(pass.expose_secret()));
}
let Ok(key) = key else { return false };
let key = PrivateKeyWithHashAlg::new(Arc::new(key), rsa_hash);
matches!(handle.authenticate_publickey(user, key).await, Ok(r) if r.success())
}
async fn try_interactive<H: Handler>(
handle: &mut Handle<H>,
user: &str,
prompts: &Arc<dyn Prompts>,
) -> bool {
let Ok(mut response) = handle
.authenticate_keyboard_interactive_start(user, None)
.await
else {
return false;
};
for _ in 0..MAX_TRIES * 2 {
match response {
KeyboardInteractiveAuthResponse::Success => return true,
KeyboardInteractiveAuthResponse::Failure { .. } => return false,
KeyboardInteractiveAuthResponse::InfoRequest {
name,
instructions,
prompts: qs,
} => {
let req = InteractiveRequest {
name,
instructions,
prompts: qs
.into_iter()
.map(|q| InteractivePrompt {
text: q.prompt,
echo: q.echo,
})
.collect(),
};
let answers = if req.prompts.is_empty() {
Vec::new()
} else {
let Some(Some(a)) = ask(prompts, move |p| p.interactive(&req)).await else {
return false;
};
a.iter().map(|s| s.expose_secret().to_owned()).collect()
};
match handle
.authenticate_keyboard_interactive_respond(answers)
.await
{
Ok(next) => response = next,
Err(_) => return false,
}
}
}
}
false
}

View file

@ -1,6 +1,9 @@
//! SFTP locations, ssh config hosts and known_hosts.
pub mod auth;
pub mod known_hosts;
mod session;
pub mod sftp;
pub mod ssh_config;
/// Shell-style glob match (`*`, `?`) on bytes, as used by ssh patterns.

View file

@ -0,0 +1,263 @@
//! Background tokio runtime and the connection manager: one SFTP session per
//! (user, host, port), reused, kept alive, reconnected after a drop and closed when idle.
use std::collections::HashMap;
use std::future::Future;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
use russh::client::{self, Handle};
use russh::keys::{HashAlg, PublicKeyOrCertificate};
use russh_sftp::client::SftpSession;
use tokio::runtime::Runtime;
use tunal_core::{Error, Result};
use crate::auth::{HostKeyInfo, Prompts, authenticate};
use crate::known_hosts::{self, HostCheck, KnownHosts};
use crate::ssh_config::Resolved;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
const KEEPALIVE: Duration = Duration::from_secs(30);
const IDLE_CLOSE: Duration = Duration::from_secs(300);
const SWEEP: Duration = Duration::from_secs(30);
fn runtime() -> &'static Runtime {
static RT: OnceLock<Runtime> = OnceLock::new();
RT.get_or_init(|| {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.thread_name("tunal-net")
.enable_all()
.build()
.expect("tokio runtime")
})
}
/// Runs `fut` on the network runtime and blocks the calling (non-runtime) thread.
pub(crate) fn block_on<T>(fut: impl Future<Output = T>) -> T {
runtime().block_on(fut)
}
/// Where a connection goes.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct ConnKey {
pub user: String,
pub host: String,
pub port: u16,
}
/// A live SSH connection with its SFTP session.
pub(crate) struct Conn {
handle: Handle<Client>,
pub sftp: SftpSession,
last_used: Mutex<Instant>,
}
impl Conn {
fn touch(&self) {
*self.last_used.lock().unwrap() = Instant::now();
}
fn alive(&self) -> bool {
!self.handle.is_closed()
}
async fn close(&self) {
let _ = self.sftp.close().await;
let _ = self
.handle
.disconnect(russh::Disconnect::ByApplication, "", "en")
.await;
}
}
/// Connection pool. Cheap to clone via `Arc`.
pub(crate) struct Pool {
conns: Mutex<HashMap<ConnKey, Arc<Conn>>>,
prompts: Arc<dyn Prompts>,
}
impl Pool {
pub fn new(prompts: Arc<dyn Prompts>) -> Arc<Self> {
let pool = Arc::new(Self {
conns: Mutex::default(),
prompts,
});
let weak = Arc::downgrade(&pool);
runtime().spawn(async move {
loop {
tokio::time::sleep(SWEEP).await;
let Some(pool) = weak.upgrade() else { return };
pool.close_idle().await;
}
});
pool
}
/// A live connection for `key`, connecting (and authenticating) when needed.
pub fn get(&self, key: &ConnKey, resolved: &Resolved) -> Result<Arc<Conn>> {
if let Some(c) = self.conns.lock().unwrap().get(key).filter(|c| c.alive()) {
c.touch();
return Ok(c.clone());
}
let conn = block_on(connect(key, resolved, &self.prompts))?;
self.conns.lock().unwrap().insert(key.clone(), conn.clone());
Ok(conn)
}
/// Forgets a connection that failed mid-operation so the next `get` reconnects.
pub fn drop_conn(&self, key: &ConnKey, conn: &Arc<Conn>) {
let mut conns = self.conns.lock().unwrap();
if conns.get(key).is_some_and(|c| Arc::ptr_eq(c, conn)) {
conns.remove(key);
}
}
/// Closes connections unused for `IDLE_CLOSE` that nothing else holds (open streams do).
async fn close_idle(&self) {
let stale: Vec<Arc<Conn>> = {
let mut conns = self.conns.lock().unwrap();
let mut out = Vec::new();
conns.retain(|_, c| {
let idle = c.last_used.lock().unwrap().elapsed() > IDLE_CLOSE;
let drop_it = !c.alive() || (idle && Arc::strong_count(c) == 1);
if drop_it {
out.push(c.clone());
}
!drop_it
});
out
};
for c in stale {
c.close().await;
}
}
}
async fn connect(
key: &ConnKey,
resolved: &Resolved,
prompts: &Arc<dyn Prompts>,
) -> Result<Arc<Conn>> {
if resolved.unsupported_proxy {
return Err(Error::Remote(
"hosts behind ProxyJump / ProxyCommand are not supported".into(),
));
}
let config = Arc::new(client::Config {
keepalive_interval: Some(KEEPALIVE),
keepalive_max: 3,
..Default::default()
});
let failure = Arc::new(Mutex::new(None));
let client = Client {
host: key.host.clone(),
port: key.port,
known: KnownHosts::load_default(),
prompts: prompts.clone(),
failure: failure.clone(),
};
let connecting = client::connect(config, (key.host.as_str(), key.port), client);
let mut handle = match tokio::time::timeout(CONNECT_TIMEOUT, connecting).await {
Err(_) => {
return Err(Error::Remote(format!(
"connecting to {} timed out",
key.host
)));
}
Ok(Err(e)) => {
let reason = failure.lock().unwrap().take();
return Err(Error::Remote(reason.unwrap_or_else(|| e.to_string())));
}
Ok(Ok(h)) => h,
};
authenticate(&mut handle, &key.user, &key.host, resolved, prompts).await?;
let remote = |e: &dyn std::fmt::Display| Error::Remote(e.to_string());
let channel = handle
.channel_open_session()
.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))?;
Ok(Arc::new(Conn {
handle,
sftp,
last_used: Mutex::new(Instant::now()),
}))
}
/// russh handler: checks the server key against known_hosts.
struct Client {
host: String,
port: u16,
known: KnownHosts,
prompts: Arc<dyn Prompts>,
/// Why the key was refused, for a readable error.
failure: Arc<Mutex<Option<String>>>,
}
impl client::Handler for Client {
type Error = russh::Error;
async fn check_server_key(
&mut self,
key: &PublicKeyOrCertificate,
) -> std::result::Result<bool, Self::Error> {
// Certificate hosts are not supported: the CA lines are ignored (S027).
let PublicKeyOrCertificate::PublicKey { key, .. } = key else {
*self.failure.lock().unwrap() = Some("host certificates are not supported".into());
return Ok(false);
};
let fingerprint = key.fingerprint(HashAlg::Sha256).to_string();
let key_type = key.algorithm().to_string();
let blob = key
.to_openssh()
.ok()
.and_then(|l| l.split_whitespace().nth(1).map(str::to_owned));
let Some(blob) = blob else { return Ok(false) };
let fail = |msg: String| *self.failure.lock().unwrap() = Some(msg);
match self.known.check(&self.host, self.port, &key_type, &blob) {
HostCheck::Match => Ok(true),
HostCheck::Mismatch => {
fail(format!(
"host key of {} changed ({fingerprint}); someone may be intercepting the connection",
self.host
));
Ok(false)
}
HostCheck::Revoked => {
fail(format!(
"host key of {} is revoked ({fingerprint})",
self.host
));
Ok(false)
}
HostCheck::Unknown => {
let info = HostKeyInfo {
host: self.host.clone(),
port: self.port,
key_type: key_type.clone(),
fingerprint,
};
let prompts = self.prompts.clone();
let ask = info.clone();
let accepted = tokio::task::spawn_blocking(move || prompts.confirm_host_key(&ask))
.await
.unwrap_or(false);
if !accepted {
fail(format!("host key of {} was not accepted", self.host));
return Ok(false);
}
if let Some(own) = known_hosts::own_file() {
let _ = known_hosts::accept_key(&own, &self.host, self.port, &key_type, &blob);
}
Ok(true)
}
}
}
}

View file

@ -0,0 +1,374 @@
//! `sftp://[user@]host[:port]/path` as a `Location` (russh + russh-sftp).
use std::io::{self, Read, Write};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use russh_sftp::client::error::Error as SftpError;
use russh_sftp::client::fs::{File, Metadata};
use russh_sftp::protocol::{FileType as WireType, OpenFlags, StatusCode};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tunal_core::mime::mime_type;
use tunal_core::{
Capabilities, Entry, Error, FileType, Kind, ListSink, Location, Result, Uri, WriteMode,
display_name,
};
use crate::auth::Prompts;
use crate::session::{Conn, ConnKey, Pool, block_on};
use crate::ssh_config::SshConfig;
/// Scheme of SFTP locations.
pub const SCHEME: &str = "sftp";
const CHUNK: usize = 256;
pub struct SftpLocation {
pool: Arc<Pool>,
config: SshConfig,
}
impl SftpLocation {
/// Reads `~/.ssh/config` once; `prompts` answers host key, password and passphrase questions.
pub fn new(prompts: Arc<dyn Prompts>) -> Self {
Self::with_config(SshConfig::load_default(), prompts)
}
pub fn with_config(config: SshConfig, prompts: Arc<dyn Prompts>) -> Self {
Self {
pool: Pool::new(prompts),
config,
}
}
/// The remote home folder of `uri`'s host (what a relative path starts from).
pub fn home(&self, uri: &Uri) -> Result<Uri> {
let home = self.op(uri, |c| block_on(c.sftp.canonicalize(".")))?;
Ok(Uri::new(SCHEME, uri.authority(), home.into_bytes()))
}
fn conn(&self, uri: &Uri) -> Result<(ConnKey, Arc<Conn>)> {
if uri.scheme() != SCHEME {
return Err(Error::Unsupported);
}
let (user, host, port) = parse_authority(uri.authority()).ok_or(Error::Unsupported)?;
let resolved = self.config.resolve(host);
let user = user
.map(str::to_owned)
.or_else(|| resolved.user.clone())
.or_else(|| std::env::var("USER").ok())
.ok_or_else(|| Error::Remote("no user name for the connection".into()))?;
let key = ConnKey {
user,
host: resolved.host_name.clone(),
port: port.unwrap_or(resolved.port),
};
let conn = self.pool.get(&key, &resolved)?;
Ok((key, conn))
}
/// Runs `f` on a live connection; a connection-level failure drops the connection and
/// retries once on a fresh one.
fn op<T>(
&self,
uri: &Uri,
f: impl Fn(&Conn) -> std::result::Result<T, SftpError>,
) -> Result<T> {
for attempt in 0..2 {
let (key, conn) = self.conn(uri)?;
match f(&conn) {
Ok(v) => return Ok(v),
Err(e) if is_connection_error(&e) => {
self.pool.drop_conn(&key, &conn);
if attempt == 1 {
return Err(map_error(e));
}
}
Err(e) => return Err(map_error(e)),
}
}
unreachable!()
}
}
/// `[user@]host[:port]`.
fn parse_authority(a: &str) -> Option<(Option<&str>, &str, Option<u16>)> {
let (user, hostport) = match a.rsplit_once('@') {
Some((u, h)) => (Some(u).filter(|u| !u.is_empty()), h),
None => (None, a),
};
let (host, port) = match hostport.rsplit_once(':') {
Some((h, p)) if !h.ends_with(']') || h.starts_with('[') => (h, Some(p.parse().ok()?)),
_ => (hostport, None),
};
let host = host.trim_start_matches('[').trim_end_matches(']');
(!host.is_empty()).then_some((user, host, port))
}
fn remote_path(uri: &Uri) -> Result<String> {
String::from_utf8(uri.path().to_vec()).map_err(|_| Error::Unsupported)
}
fn is_connection_error(e: &SftpError) -> bool {
match e {
SftpError::IO(_) | SftpError::Timeout => true,
SftpError::Status(s) => matches!(
s.status_code,
StatusCode::NoConnection | StatusCode::ConnectionLost
),
_ => false,
}
}
fn map_error(e: SftpError) -> Error {
match &e {
SftpError::Status(s) => match s.status_code {
StatusCode::NoSuchFile => Error::NotFound,
StatusCode::PermissionDenied => Error::PermissionDenied,
StatusCode::OpUnsupported => Error::Unsupported,
_ => Error::Remote(e.to_string()),
},
_ => Error::Remote(e.to_string()),
}
}
fn wire_kind(m: &Metadata) -> FileType {
match m.file_type() {
WireType::Dir => FileType::Dir,
WireType::File => FileType::File,
_ => FileType::Special,
}
}
fn entry(name: Vec<u8>, m: &Metadata, link: Option<(Vec<u8>, Option<FileType>)>) -> Entry {
let kind = match (link, m.file_type()) {
(Some((target, target_type)), _) => Kind::Symlink {
target,
target_type,
},
(None, WireType::Dir) => Kind::Dir,
(None, WireType::File) => Kind::File,
(None, _) => Kind::Special,
};
Entry {
display_name: display_name(&name),
hidden: name.first() == Some(&b'.'),
mime: mime_type(&name, &kind),
kind,
size: m.size.unwrap_or(0),
mtime: m
.mtime
.map(|t| SystemTime::UNIX_EPOCH + Duration::from_secs(t.into())),
mode: m.permissions.unwrap_or(0) & 0o7777,
uid: m.uid.unwrap_or(0),
gid: m.gid.unwrap_or(0),
name,
}
}
/// Link target and target type for a symlink at `path`.
async fn link_info(conn: &Conn, path: &str) -> (Vec<u8>, Option<FileType>) {
let target = conn
.sftp
.read_link(path)
.await
.map(String::into_bytes)
.unwrap_or_default();
let target_type = conn.sftp.metadata(path).await.ok().map(|m| wire_kind(&m));
(target, target_type)
}
async fn lstat_entry(
conn: &Conn,
path: &str,
name: Vec<u8>,
) -> std::result::Result<Entry, SftpError> {
let m = conn.sftp.symlink_metadata(path).await?;
let link = if m.file_type() == WireType::Symlink {
Some(link_info(conn, path).await)
} else {
None
};
Ok(entry(name, &m, link))
}
impl Location for SftpLocation {
fn scheme(&self) -> &str {
SCHEME
}
fn capabilities(&self) -> Capabilities {
Capabilities {
write: true,
trash: false,
symlink: true,
watch: false,
permissions: true,
}
}
fn list(&self, dir: &Uri, sink: &mut ListSink<'_>) -> Result<()> {
let path = remote_path(dir)?;
let entries = self.op(dir, |c| {
block_on(async {
let mut out = Vec::new();
for e in c.sftp.read_dir(path.as_str()).await? {
let name = e.file_name();
if name == "." || name == ".." {
continue;
}
let m = e.metadata();
let link = if m.file_type() == WireType::Symlink {
Some(link_info(c, &e.path()).await)
} else {
None
};
out.push(entry(name.into_bytes(), &m, link));
}
Ok(out)
})
})?;
let mut entries = entries.into_iter().peekable();
while entries.peek().is_some() {
let chunk: Vec<Entry> = entries.by_ref().take(CHUNK).collect();
if sink(chunk).is_break() {
return Err(Error::Cancelled);
}
}
Ok(())
}
fn stat(&self, uri: &Uri) -> Result<Entry> {
let path = remote_path(uri)?;
let name = uri.file_name().unwrap_or(b"/").to_vec();
self.op(uri, |c| block_on(lstat_entry(c, &path, name.clone())))
}
fn open_read(&self, uri: &Uri) -> Result<Box<dyn Read + Send>> {
let path = remote_path(uri)?;
let (key, conn) = self.conn(uri)?;
let file = block_on(conn.sftp.open(path)).map_err(|e| {
if is_connection_error(&e) {
self.pool.drop_conn(&key, &conn);
}
map_error(e)
})?;
Ok(Box::new(Remote {
_conn: conn,
file: Some(file),
}))
}
fn open_write(&self, uri: &Uri, mode: WriteMode) -> Result<Box<dyn Write + Send>> {
let path = remote_path(uri)?;
let flags = match mode {
WriteMode::CreateNew => OpenFlags::CREATE | OpenFlags::WRITE | OpenFlags::EXCLUDE,
WriteMode::Overwrite => OpenFlags::CREATE | OpenFlags::WRITE | OpenFlags::TRUNCATE,
};
let (key, conn) = self.conn(uri)?;
let file = block_on(conn.sftp.open_with_flags(path, flags)).map_err(|e| {
if is_connection_error(&e) {
self.pool.drop_conn(&key, &conn);
}
match (&e, mode) {
// The server answers a failed O_EXCL open with a plain failure.
(SftpError::Status(s), WriteMode::CreateNew)
if s.status_code == StatusCode::Failure =>
{
Error::Exists
}
_ => map_error(e),
}
})?;
Ok(Box::new(Remote {
_conn: conn,
file: Some(file),
}))
}
fn mkdir(&self, uri: &Uri) -> Result<()> {
let path = remote_path(uri)?;
if self.op(uri, |c| block_on(c.sftp.try_exists(path.as_str())))? {
return Err(Error::Exists);
}
self.op(uri, |c| block_on(c.sftp.create_dir(path.as_str())))
}
fn rename(&self, from: &Uri, to: &Uri) -> Result<()> {
if from.authority() != to.authority() || to.scheme() != SCHEME {
return Err(Error::Unsupported);
}
let (a, b) = (remote_path(from)?, remote_path(to)?);
// Plain SFTP rename may replace or fail depending on the server: check first.
if self
.op(to, |c| block_on(c.sftp.symlink_metadata(b.as_str())))
.is_ok()
{
return Err(Error::Exists);
}
self.op(from, |c| block_on(c.sftp.rename(a.as_str(), b.as_str())))
}
fn delete(&self, uri: &Uri) -> Result<()> {
let path = remote_path(uri)?;
self.op(uri, |c| {
block_on(async {
if c.sftp.symlink_metadata(path.as_str()).await?.file_type() == WireType::Dir {
c.sftp.remove_dir(path.as_str()).await
} else {
c.sftp.remove_file(path.as_str()).await
}
})
})
}
fn symlink(&self, link: &Uri, target: &[u8]) -> Result<()> {
let path = remote_path(link)?;
let target = String::from_utf8(target.to_vec()).map_err(|_| Error::Unsupported)?;
// OpenSSH's sftp-server reads the two names in swapped order (unlike the spec).
self.op(link, |c| {
block_on(c.sftp.symlink(target.as_str(), path.as_str()))
})
}
}
/// A remote file as blocking `Read` / `Write`. Holds the connection open while in use.
struct Remote {
_conn: Arc<Conn>,
file: Option<File>,
}
impl Remote {
fn file(&mut self) -> io::Result<&mut File> {
self.file
.as_mut()
.ok_or_else(|| io::Error::from(io::ErrorKind::BrokenPipe))
}
}
impl Read for Remote {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let file = self.file()?;
block_on(file.read(buf))
}
}
impl Write for Remote {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let file = self.file()?;
block_on(file.write(buf))
}
fn flush(&mut self) -> io::Result<()> {
let file = self.file()?;
block_on(file.flush())
}
}
impl Drop for Remote {
fn drop(&mut self) {
if let Some(mut file) = self.file.take() {
let _ = block_on(file.shutdown());
}
}
}

View file

@ -210,6 +210,14 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done,
- Not done: no iPhone (D-009, S036): pairing, Trust prompt, AFC ops, eject, names all unchecked live. Symlinks shown with unknown target type. main.rs still names the backends `mtp` (left to avoid S021's file).
- Later: eject for MTP phones; device name in breadcrumb; free space via AFC device info; a "Connecting…" entry shows the default name "iPhone" until lockdown answers.
## S028 — SFTP location
- Done: `tunal-net` `sftp::SftpLocation::new(Arc<dyn Prompts>)` (`with_config`, `home(uri)`), scheme `sftp`, authority `[user@]host[:port]` (host may be an ssh_config alias; user falls back to config, then $USER). Register it with `Locations::register`. Caps: write, symlink, permissions; no trash/watch. `session.rs`: own 2-thread tokio runtime (`tunal-net` threads), pool per (user, host, port): reuse, keepalive 30 s (3 misses), dead connection replaced on next use, one retry on a connection error, idle close after 5 min when nothing holds it. `auth.rs`: agent (IdentitiesOnly filters by `.pub`) → identity files (config, else id_ed25519/ecdsa/rsa; passphrase prompt, 3 tries) → password (3 tries) → keyboard-interactive. Host key via S027 `check`; Unknown → `Prompts::confirm_host_key` then `accept_key` to own file; Mismatch/Revoked/certificate → `Error::Remote` message. Reads and writes are pipelined by russh-sftp (16 in flight); `Remote` is blocking `Read`/`Write` (flush before drop to see write errors).
- Prompt API (`auth::Prompts`, all blocking, called on a worker thread, defaults refuse): `confirm_host_key(&HostKeyInfo{host,port,key_type,fingerprint})`, `password(user, host)`, `passphrase(&Path)`, `interactive(&InteractiveRequest{name,instructions,prompts[{text,echo}]})`; answers are `secrecy::SecretString`. `NoPrompts` refuses all.
- Deps (workspace): russh 0.65 (ring, no aws-lc-rs), russh-sftp 3, secrecy 0.10, zeroize 1, tokio +sync. Example `sftp-ls -- <uri>` (terminal prompts).
- Verified: tunal-net build, clippy -D warnings, fmt --check; `cargo tree -i aws-lc-rs` empty; secret grep empty; against a local sshd (port 2299, scratch HOME, key auth): list + symlink entries, accept then silent reuse, changed key = hard error, refuse = error, mkdir/exists, create-new/overwrite, 3 MB write+read roundtrip equal, rename (Exists on clash), delete, symlink, home. Workspace clippy fails only on S023's unfinished `player_bridge` module.
- Not done: password and keyboard-interactive paths (local sshd had keys only), agent auth, passphrase keys, ProxyJump (reported unsupported); `posix-rename` not used (library hides offered extensions; rename pre-checks the target instead, so overwriting needs delete first); non-UTF-8 remote paths give `Unsupported`; `NotEmpty` not reported (server says failure); russh keeps its own copy of the password string, not zeroized. Real host check is S036.
- Later: posix-rename via the raw session; watch by polling.
## Later
- (orchestrator) Breadcrumb: a long path is hard-clipped at the bar's left edge with no elision mark, and the root crumb elides at 960 px — for S034.
-