From c5c2fb7c986bd529776ed54cb9f7282d2c1dd5ff Mon Sep 17 00:00:00 2001 From: Gabriel Gondim <52431033+GGVidal@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:03:04 -0300 Subject: [PATCH] fix(ssh): use the agent from IdentityAgent or the login shell's SSH_AUTH_SOCK (#4939) OpenSSH authentication asked the agent client for SSH_AUTH_SOCK from the process environment only. On macOS an app started from the Dock has launchd's socket there, so an agent exported in ~/.zshrc (Bitwarden's, in #4934) was never used. The default agent is now SSH_AUTH_SOCK as the login shell sets it (the app already reads that environment at startup), and IdentityAgent in ~/.ssh/config is honoured per host, jump hosts included (none, SSH_AUTH_SOCK, $VAR or a path with ~ and % tokens). On Windows a SSH_AUTH_SOCK that is not a pipe falls back to the OpenSSH pipe. Co-authored-by: GGVidal <52431033+GGVidal@users.noreply.github.com> --- crates/ide-ssh/src/session.rs | 10 ++-- crates/ide-ssh/src/target.rs | 96 ++++++++++++++++++++++++++++++++++- docs/en/guide/remote/ssh.mdx | 5 +- docs/zh/guide/remote/ssh.mdx | 5 +- 4 files changed, 109 insertions(+), 7 deletions(-) diff --git a/crates/ide-ssh/src/session.rs b/crates/ide-ssh/src/session.rs index df82ac802..9ea118da4 100644 --- a/crates/ide-ssh/src/session.rs +++ b/crates/ide-ssh/src/session.rs @@ -640,11 +640,13 @@ async fn with_key(handle: &mut Handle, user: &str, key: keys::PrivateKey } /// Every identity of the running SSH agent, until one is accepted. -async fn with_agent(handle: &mut Handle, user: &str) -> bool { +async fn with_agent(handle: &mut Handle, hop: &Hop) -> bool { + let user = hop.user.as_str(); + let Some(socket) = hop.agent.socket() else { return false }; #[cfg(unix)] - let agent = keys::agent::client::AgentClient::connect_env().await; + let agent = keys::agent::client::AgentClient::connect_uds(socket).await; #[cfg(windows)] - let agent = keys::agent::client::AgentClient::connect_named_pipe(r"\\.\pipe\openssh-ssh-agent").await; + let agent = keys::agent::client::AgentClient::connect_named_pipe(socket).await; let Ok(mut agent) = agent else { return false }; let Ok(identities) = agent.request_identities().await else { return false }; let hash = rsa_hash(handle).await; @@ -693,7 +695,7 @@ async fn authenticate( if handle.authenticate_none(user).await.map(|r| r.success()).unwrap_or(false) { return Ok(()); } - if with_agent(handle, user).await { + if with_agent(handle, hop).await { return Ok(()); } let files: Vec = if hop.identity_files.is_empty() { diff --git a/crates/ide-ssh/src/target.rs b/crates/ide-ssh/src/target.rs index b9095b3f0..baa40579e 100644 --- a/crates/ide-ssh/src/target.rs +++ b/crates/ide-ssh/src/target.rs @@ -53,6 +53,65 @@ pub(crate) struct Hop { pub proxy_command: Option, pub host_key_policy: HostKeyPolicy, pub known_hosts: Option, + pub agent: Agent, +} + +/// Where the SSH agent of a hop listens (`IdentityAgent`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Agent { + /// `SSH_AUTH_SOCK` (the OpenSSH pipe on Windows when it is unset). + Default, + /// `IdentityAgent none`, or an unset `$VARIABLE`. + Off, + Socket(PathBuf), +} + +impl Agent { + /// The socket (or Windows pipe) to connect to, `None` for no agent. + pub fn socket(&self) -> Option { + match self { + Agent::Off => None, + Agent::Socket(path) => Some(path.clone()), + Agent::Default => { + let var = env_var("SSH_AUTH_SOCK").filter(|v| !v.is_empty()).map(PathBuf::from); + if cfg!(windows) { + // Only a pipe works there; a Unix socket path comes from MSYS or WSL tools. + let pipe = var.filter(|p| p.to_string_lossy().starts_with(r"\\.\pipe\")); + Some(pipe.unwrap_or_else(|| PathBuf::from(r"\\.\pipe\openssh-ssh-agent"))) + } else { + var + } + } + } + } +} + +/// A variable as the user's shell sees it. An app started from Finder or the Dock has the +/// login session's environment; the shell's rc files may set another value (an SSH agent +/// socket exported in `~/.zshrc`), and that is the one `ssh` in a terminal uses. +fn env_var(name: &str) -> Option { + ide_core::process::login_env() + .and_then(|vars| vars.iter().find(|(k, _)| k == name).map(|(_, v)| v.clone())) + .or_else(|| std::env::var_os(name)) +} + +/// `IdentityAgent`: `none`, `SSH_AUTH_SOCK`, `$VARIABLE`, or a path (`~` and `%` tokens expanded). +fn identity_agent(value: Option<&str>, expand_path: impl Fn(&str) -> PathBuf) -> Agent { + let Some(value) = value.map(str::trim).filter(|v| !v.is_empty()) else { return Agent::Default }; + if value.eq_ignore_ascii_case("none") { + return Agent::Off; + } + if value == "SSH_AUTH_SOCK" { + return Agent::Default; + } + if let Some(name) = value.strip_prefix('$') { + let name = name.strip_prefix('{').and_then(|n| n.strip_suffix('}')).unwrap_or(name); + return match env_var(name).filter(|v| !v.is_empty()) { + Some(path) => Agent::Socket(expand(&path.to_string_lossy())), + None => Agent::Off, + }; + } + Agent::Socket(expand_path(value)) } /// `StrictHostKeyChecking`: what happens to a host key missing from `known_hosts`. @@ -98,6 +157,7 @@ struct RawConfig { proxy_command: Option, host_key_policy: Option, user_known_hosts_file: Option, + identity_agent: Option, } fn strip_quotes(s: &str) -> &str { @@ -444,6 +504,11 @@ fn parse_config_file( }); } } + "identityagent" => { + if out.identity_agent.is_none() { + out.identity_agent = Some(strip_quotes(value).to_owned()); + } + } "userknownhostsfile" => { if out.user_known_hosts_file.is_none() && let Some(first) = split_args(value).into_iter().next() @@ -492,7 +557,9 @@ fn config_hop( }; let host_key_policy = if null_known_hosts { HostKeyPolicy::Off } else { raw.host_key_policy.unwrap_or(HostKeyPolicy::Ask) }; - let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts }; + let agent = + identity_agent(raw.identity_agent.as_deref(), |p| expand(&expand_tokens(p, alias, &host, port, &user, &local))); + let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts, agent }; (hop, proxy_jump) } @@ -529,6 +596,7 @@ pub(crate) fn resolve_hops(target: &SshTarget, config: Option<&Path>) -> IdeResu proxy_command: None, host_key_policy: HostKeyPolicy::Ask, known_hosts: None, + agent: Agent::Default, }, None, ) @@ -594,6 +662,32 @@ mod tests { assert!(resolve_hops(&SshTarget::default(), None).is_err()); } + #[test] + fn identity_agent_picks_the_agent_of_each_hop() { + let tmp = tempfile::tempdir().unwrap(); + let config = tmp.path().join("config"); + std::fs::write( + &config, + "Host vault\n IdentityAgent \"~/agents/%h.sock\"\n ProxyJump plain\n\n\ + Host off\n IdentityAgent none\n\nHost shell\n IdentityAgent ${OPENIDEA_TEST_AGENT}\n\n\ + Host unset\n IdentityAgent $OPENIDEA_TEST_UNSET_AGENT\n\nHost env\n IdentityAgent SSH_AUTH_SOCK\n", + ) + .unwrap(); + // Exported only by the shell's rc files, as a GUI app sees it (#4934). + ide_core::process::set_shell_env(vec![("OPENIDEA_TEST_AGENT".into(), "/run/agent.sock".into())]); + let agent = |host: &str| { + let target = SshTarget { host: host.into(), auth: SshAuth::OpenSsh, ..Default::default() }; + resolve_hops(&target, Some(&config)).unwrap().into_iter().map(|h| h.agent).collect::>() + }; + let home = home().unwrap(); + assert_eq!(agent("vault"), [Agent::Default, Agent::Socket(home.join("agents/vault.sock"))]); + assert_eq!(agent("off"), [Agent::Off]); + assert_eq!(agent("shell"), [Agent::Socket("/run/agent.sock".into())]); + assert_eq!(agent("unset"), [Agent::Off]); + assert_eq!(agent("env"), [Agent::Default]); + assert_eq!(Agent::Off.socket(), None); + } + #[test] fn resolves_include_match_equals_and_proxy_command() { let tmp = tempfile::tempdir().unwrap(); diff --git a/docs/en/guide/remote/ssh.mdx b/docs/en/guide/remote/ssh.mdx index 460462add..4893d89a6 100644 --- a/docs/en/guide/remote/ssh.mdx +++ b/docs/en/guide/remote/ssh.mdx @@ -49,10 +49,13 @@ never to a settings file. The **+**, **−** and copy buttons above the list add ### `~/.ssh/config` support OpenIDEA has its own SSH client and reads `~/.ssh/config` itself. It understands `Host`, `Match`, `Include`, -`HostName`, `User`, `Port`, `IdentityFile`, `ProxyJump`, `ProxyCommand`, `StrictHostKeyChecking` and +`HostName`, `User`, `Port`, `IdentityFile`, `IdentityAgent`, `ProxyJump`, `ProxyCommand`, `StrictHostKeyChecking` and `UserKnownHostsFile`. Jump hosts authenticate with the agent and identity files; the password or passphrase of the configuration is only used for the target host. +The SSH agent is the one `IdentityAgent` names, otherwise `SSH_AUTH_SOCK` as your login shell sets it, so an agent +socket exported in `~/.zshrc` (for example a password manager's agent) works even when OpenIDEA is started from the Dock. + Host keys are checked against `known_hosts`. An unknown key has to be trusted once; a changed key is refused unless host key checking is turned off for that host. diff --git a/docs/zh/guide/remote/ssh.mdx b/docs/zh/guide/remote/ssh.mdx index 3ff1d2be1..496a5a03f 100644 --- a/docs/zh/guide/remote/ssh.mdx +++ b/docs/zh/guide/remote/ssh.mdx @@ -41,9 +41,12 @@ OpenIDEA 通过 SSH 连接;在 Windows 上也可以直接连入 WSL 发行版 ### `~/.ssh/config` 支持 OpenIDEA 自带 SSH 客户端,自行读取 `~/.ssh/config`,支持 `Host`、`Match`、`Include`、`HostName`、`User`、`Port`、 -`IdentityFile`、`ProxyJump`、`ProxyCommand`、`StrictHostKeyChecking` 和 `UserKnownHostsFile`。跳板机通过代理和身份文件认证, +`IdentityFile`、`IdentityAgent`、`ProxyJump`、`ProxyCommand`、`StrictHostKeyChecking` 和 `UserKnownHostsFile`。跳板机通过代理和身份文件认证, 配置里的密码或密码短语只用于目标主机。 +SSH 代理使用 `IdentityAgent` 指定的那个,未指定时使用登录 shell 设置的 `SSH_AUTH_SOCK`,所以在 `~/.zshrc` 里导出的代理 socket +(例如密码管理器的 SSH 代理)在从程序坞启动 OpenIDEA 时也能用。 + 主机密钥会与 `known_hosts` 比对。未知密钥需要先信任一次;密钥发生变化时会拒绝连接,除非对该主机关闭了主机密钥检查。 ## 打开远程项目