diff --git a/docs/architecture/remote-workspace-transport.md b/docs/architecture/remote-workspace-transport.md index 55e9624f8a..268e9cafef 100644 --- a/docs/architecture/remote-workspace-transport.md +++ b/docs/architecture/remote-workspace-transport.md @@ -285,7 +285,11 @@ to searching the controller filesystem. ## Authentication and secrets Supported target methods are password, private key, private key plus OpenSSH -certificate, OpenSSH agent, and keyboard-interactive responses. +certificate, OpenSSH agent, keyboard-interactive responses, and the SSH `none` +method for endpoints whose transport is already authenticated (a Coder +workspace agent, for example). `none` is an explicit profile choice: it is +never tried as a fallback, and a rejected `none` profile never turns into a +credential prompt. - Passwords use the existing encrypted password vault. - Private-key paths, certificate paths, and auth method metadata may be saved. @@ -504,6 +508,15 @@ Local Docker profiles may legitimately retain an empty legacy password placeholder. Connection, testing, and local container discovery do not require a password-vault entry for those profiles. +`SavedAuthType::None` is unknown to earlier builds, which parse +`ssh_connections.json` as one list and rewrite it from memory. Those profiles +therefore live in `ssh_connections_extended.json`, which earlier builds neither +read nor write; the primary file keeps the shape they understand. Loading merges +both files, and the primary entry wins when an earlier build recreated the same +ID. An earlier build does not list these profiles until the user upgrades again. +Peer controllers reject `None` before RPC unless the host advertises +`ssh_none_auth_v1`. + Startup recovery never deletes a profile or workspace merely because a credential is unavailable, a connection times out, or a remote host is temporarily offline. Destructive removal remains an explicit user action. diff --git a/docs/features/remote-workspaces.md b/docs/features/remote-workspaces.md index 7afa6ce492..ec2d4c49eb 100644 --- a/docs/features/remote-workspaces.md +++ b/docs/features/remote-workspaces.md @@ -44,6 +44,11 @@ ssh-agent identity. Explicit password and keyboard-interactive challenge responses are also supported, with configurable connection/authentication timeouts, whole-chain retries, and challenge-round limits. +Choose **No authentication** only for endpoints that accept the SSH `none` +method because the tunnel is already authenticated, such as a Coder workspace +agent. OpenBitFun never falls back to it, and it never falls back from it to a +password or key. + ## Docker targets For **Remote host → Container → Through the Docker host**, OpenBitFun first establishes the SSH connection (and diff --git a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json index 8de65fd4de..a207d54f91 100644 --- a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json +++ b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "digest": "fnv1a64:feb182159a7e227e", + "digest": "fnv1a64:33ad4ddb17680c30", "retiredCommandPrefixes": [ { "prefix": "lsp_", @@ -51,6 +51,7 @@ "session_trajectory_v1", "user_question_response", "user_question_interaction_v1", + "ssh_none_auth_v1", "terminal_cursor_replay_v1" ], "desktop": [ @@ -95,7 +96,8 @@ "whole_session_copy_v1", "session_trajectory_v1", "user_question_response", - "user_question_interaction_v1" + "user_question_interaction_v1", + "ssh_none_auth_v1" ], "cli": [ "model_routing_v1", diff --git a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs index f16e8758b3..e91b88c807 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs @@ -107,6 +107,9 @@ pub enum PeerHostCapability { UserQuestionResponse, /// First human interaction disables the unattended question timeout. UserQuestionInteractionV1, + /// SSH profiles may use the `None` authentication method. A host without + /// this key cannot parse such a profile. + SshNoneAuthV1, /// Terminal output is read as bounded `terminal_get_history` pages announced /// on the `terminal-` host stream instead of `terminal_event` fan-out. /// This selects a delivery path, so only a host using that path advertises it. @@ -158,6 +161,7 @@ impl PeerHostCapability { Self::SessionTrajectoryV1, Self::UserQuestionResponse, Self::UserQuestionInteractionV1, + Self::SshNoneAuthV1, Self::TerminalCursorReplayV1, ]; @@ -206,6 +210,7 @@ impl PeerHostCapability { Self::WholeSessionCopyV1 => "whole_session_copy_v1", Self::UserQuestionResponse => "user_question_response", Self::UserQuestionInteractionV1 => "user_question_interaction_v1", + Self::SshNoneAuthV1 => "ssh_none_auth_v1", Self::TerminalCursorReplayV1 => "terminal_cursor_replay_v1", } } @@ -261,6 +266,7 @@ const DESKTOP_CAPABILITIES: &[PeerHostCapability] = &[ PeerHostCapability::SessionTrajectoryV1, PeerHostCapability::UserQuestionResponse, PeerHostCapability::UserQuestionInteractionV1, + PeerHostCapability::SshNoneAuthV1, ]; /// The CLI peer host has no MiniApp runtime, WSL or SSH connection setup, diff --git a/src/crates/services/services-integrations/src/remote_persistence.rs b/src/crates/services/services-integrations/src/remote_persistence.rs index d96788e167..91cbac75e5 100644 --- a/src/crates/services/services-integrations/src/remote_persistence.rs +++ b/src/crates/services/services-integrations/src/remote_persistence.rs @@ -600,6 +600,9 @@ pub enum SavedAuthTypeRecord { fallback_key_path: Option, }, KeyboardInteractive, + /// Server accepts the connection without credentials; kept in sync with + /// `remote_ssh::types::SavedAuthType::None` so migrated profiles survive. + None, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] diff --git a/src/crates/services/services-integrations/src/remote_ssh/manager.rs b/src/crates/services/services-integrations/src/remote_ssh/manager.rs index 97cce2022d..74295bfff2 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/manager.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/manager.rs @@ -1459,6 +1459,13 @@ async fn authenticate_handle( SSHAuthMethod::KeyboardInteractive { responses } => { authenticate_keyboard_interactive(handle, config, stage, responses).await? } + // Endpoints whose transport is already authenticated (Coder workspace + // agents) advertise only `none` and disconnect clients that send + // credentials, so this must be an explicit choice rather than a fallback. + SSHAuthMethod::None => handle + .authenticate_none(&config.username) + .await + .map_err(|error| anyhow!("{} none authentication failed: {:?}", stage, error))?, }) }; let authenticated = tokio::time::timeout( @@ -2240,6 +2247,7 @@ pub struct SSHConnectionManager { reconnect_locks: Arc>>>>, saved_connections: Arc>>, config_path: std::path::PathBuf, + extended_config_path: std::path::PathBuf, /// Known hosts storage known_hosts: Arc>>, known_hosts_path: std::path::PathBuf, @@ -2249,10 +2257,18 @@ pub struct SSHConnectionManager { password_vault: std::sync::Arc, } +/// Saved profiles that released builds cannot read; see `save_connections`. +const EXTENDED_SAVED_CONNECTIONS_FILE: &str = "ssh_connections_extended.json"; + +fn requires_extended_store(auth_type: &crate::remote_ssh::types::SavedAuthType) -> bool { + matches!(auth_type, crate::remote_ssh::types::SavedAuthType::None) +} + impl SSHConnectionManager { /// Create a new SSH connection manager pub fn new(data_dir: std::path::PathBuf) -> Self { let config_path = data_dir.join("ssh_connections.json"); + let extended_config_path = data_dir.join(EXTENDED_SAVED_CONNECTIONS_FILE); let known_hosts_path = data_dir.join("known_hosts"); let remote_workspace_path = data_dir.join("remote_workspace.json"); let password_vault = std::sync::Arc::new(SSHPasswordVault::new(data_dir)); @@ -2261,6 +2277,7 @@ impl SSHConnectionManager { reconnect_locks: Arc::new(tokio::sync::RwLock::new(HashMap::new())), saved_connections: Arc::new(tokio::sync::RwLock::new(Vec::new())), config_path, + extended_config_path, known_hosts: Arc::new(tokio::sync::RwLock::new(HashMap::new())), known_hosts_path, remote_workspaces: Arc::new(tokio::sync::RwLock::new(Vec::new())), @@ -2822,17 +2839,43 @@ impl SSHConnectionManager { self.config_path.exists() ); - if !self.config_path.exists() { - return Ok(()); - } + // Read the extended store first: a damaged primary file must not leave + // an empty list behind that the next save writes over these profiles. + let extended = self.read_extended_saved_connections().await; + let saved = match self.read_primary_saved_connections().await { + Ok(saved) => saved, + Err(error) => { + *self.saved_connections.write().await = extended; + return Err(error); + } + }; - let content = tokio::fs::read_to_string(&self.config_path).await?; - log::info!("load_saved_connections: content={}", content); - let saved: Vec = - serde_json::from_str(&content).context("Failed to parse saved SSH connections")?; + // An older build may have recreated an id while it could not see the + // extended store; that later explicit save wins. + let mut merged = saved; + for connection in extended { + // Same rule as `save_connection`: an equal id, or a legacy + // `:port` alias of the same endpoint. + if merged.iter().any(|existing| { + existing.id == connection.id + || (existing.host == connection.host + && existing.username == connection.username + && existing.port == connection.port + && existing.container == connection.container + && existing.wsl == connection.wsl + && Self::connection_ids_are_aliases(&existing.id, &connection.id)) + }) { + log::warn!( + "Ignoring extended SSH profile shadowed by the primary store: id={}", + connection.id + ); + } else { + merged.push(connection); + } + } let mut guard = self.saved_connections.write().await; - *guard = saved; + *guard = merged; drop(guard); let unavailable = self.saved_connections_without_credentials().await; @@ -2848,11 +2891,57 @@ impl SSHConnectionManager { Ok(()) } + async fn read_primary_saved_connections(&self) -> anyhow::Result> { + if !self.config_path.exists() { + return Ok(Vec::new()); + } + let content = tokio::fs::read_to_string(&self.config_path).await?; + log::info!("load_saved_connections: content={}", content); + serde_json::from_str(&content).context("Failed to parse saved SSH connections") + } + + /// Read the extended store, setting an unreadable file aside so it stays + /// recoverable and a later save cannot overwrite it. + async fn read_extended_saved_connections(&self) -> Vec { + let path = &self.extended_config_path; + if !path.exists() { + return Vec::new(); + } + let parsed = tokio::fs::read_to_string(path) + .await + .map_err(anyhow::Error::from) + .and_then(|content| serde_json::from_str(&content).map_err(anyhow::Error::from)); + let error = match parsed { + Ok(saved) => return saved, + Err(error) => error, + }; + let backup = path.with_extension("json.unreadable"); + log::warn!( + "Failed to read extended SSH connections; keeping the file at {:?}: error={}", + backup, + error + ); + if let Err(error) = tokio::fs::rename(path, &backup).await { + log::warn!( + "Failed to set aside extended SSH connections: error={}", + error + ); + } + Vec::new() + } + /// Save connections to disk + /// + /// Released builds parse the primary file as one list and rewrite it from + /// memory, so a profile they cannot deserialize would cost them every + /// profile. Such profiles go to the extended store, which they never touch. async fn save_connections(&self) -> anyhow::Result<()> { log::info!("save_connections: saving to {:?}", self.config_path); let guard = self.saved_connections.read().await; - let content = serde_json::to_string_pretty(&*guard)?; + let (extended, primary): (Vec<&SavedConnection>, Vec<&SavedConnection>) = guard + .iter() + .partition(|connection| requires_extended_store(&connection.auth_type)); + let content = serde_json::to_string_pretty(&primary)?; log::info!("save_connections: content={}", content); // Ensure parent directory exists @@ -2860,6 +2949,10 @@ impl SSHConnectionManager { tokio::fs::create_dir_all(parent).await?; } + if !extended.is_empty() || self.extended_config_path.exists() { + let extended_content = serde_json::to_string_pretty(&extended)?; + tokio::fs::write(&self.extended_config_path, extended_content).await?; + } tokio::fs::write(&self.config_path, content).await?; log::info!( "save_connections: saved {} connections to {:?}", @@ -2947,7 +3040,12 @@ impl SSHConnectionManager { (SSHAuthMethod::PrivateKey { .. }, false) => { self.password_vault.remove(&config.id).await?; } - (SSHAuthMethod::Agent { .. } | SSHAuthMethod::KeyboardInteractive { .. }, false) => { + ( + SSHAuthMethod::Agent { .. } + | SSHAuthMethod::KeyboardInteractive { .. } + | SSHAuthMethod::None, + false, + ) => { self.password_vault.remove(&config.id).await?; } } @@ -2999,6 +3097,7 @@ impl SSHConnectionManager { SSHAuthMethod::KeyboardInteractive { .. } => { crate::remote_ssh::types::SavedAuthType::KeyboardInteractive } + SSHAuthMethod::None => crate::remote_ssh::types::SavedAuthType::None, }, default_workspace: config.default_workspace.clone(), last_connected: Some(chrono::Utc::now().timestamp() as u64), @@ -4639,6 +4738,7 @@ impl SSHConnectionManager { responses: Vec::new(), } } + crate::remote_ssh::types::SavedAuthType::None => SSHAuthMethod::None, }; Ok(Some(SSHConnectionConfig { @@ -10026,6 +10126,483 @@ Host * let _ = tokio::fs::remove_dir_all(&dir).await; } + #[tokio::test] + async fn saved_none_auth_profile_round_trips_without_credentials() { + let dir = test_data_dir("none-auth-profile"); + tokio::fs::create_dir_all(&dir).await.unwrap(); + let manager = SSHConnectionManager::new(dir.clone()); + + manager + .save_connection(&SSHConnectionConfig { + id: "ssh-coder@127.0.0.1".to_string(), + name: "coder agent".to_string(), + host: "127.0.0.1".to_string(), + port: 2222, + username: "coder".to_string(), + auth: SSHAuthMethod::None, + default_workspace: Some("/root".to_string()), + proxy_jump: None, + proxy_command: None, + container: None, + wsl: None, + options: Default::default(), + }) + .await + .unwrap(); + + let persisted = tokio::fs::read_to_string(dir.join(EXTENDED_SAVED_CONNECTIONS_FILE)) + .await + .unwrap(); + assert!( + persisted.contains("\"None\""), + "saved profile must record the none method: {persisted}" + ); + assert!( + !manager.has_stored_password("ssh-coder@127.0.0.1").await, + "none authentication must not create a password vault entry" + ); + + let restored = manager + .load_connection_config_from_saved("ssh-coder@127.0.0.1") + .await + .unwrap() + .unwrap(); + assert!(matches!(restored.auth, SSHAuthMethod::None)); + + // Empty bodies are the shape the web UI sends for a new profile. + let from_wire: SSHConnectionConfig = serde_json::from_value(serde_json::json!({ + "id": "ssh-coder@127.0.0.1", + "name": "coder agent", + "host": "127.0.0.1", + "port": 2222, + "username": "coder", + "auth": { "type": "None" }, + "defaultWorkspace": null, + })) + .unwrap(); + assert!(matches!(from_wire.auth, SSHAuthMethod::None)); + let _ = tokio::fs::remove_dir_all(&dir).await; + } + + struct NoneOnlyTestServer { + none_attempts: Arc, + } + + #[async_trait] + impl russh::server::Handler for NoneOnlyTestServer { + type Error = russh::Error; + + async fn auth_none(&mut self, _user: &str) -> Result { + self.none_attempts.fetch_add(1, Ordering::SeqCst); + Ok(russh::server::Auth::Accept) + } + } + + fn nc_on_path() -> bool { + std::env::var_os("PATH").is_some_and(|paths| { + std::env::split_paths(&paths).any(|path| path.join("nc").is_file()) + }) + } + + /// The Coder shape: the transport is a local process and the endpoint + /// advertises only `none`, so any other method would fail the connection. + #[cfg(unix)] + #[tokio::test] + async fn none_auth_over_proxy_command_connects_after_restoring_the_saved_profile() { + if !nc_on_path() { + return; + } + let dir = test_data_dir("none-auth-proxy-command"); + tokio::fs::create_dir_all(&dir).await.unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let none_attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let server_attempts = none_attempts.clone(); + let server = tokio::spawn(async move { + let (socket, _) = listener.accept().await.unwrap(); + let config = Arc::new(russh::server::Config { + keys: vec![KeyPair::generate_ed25519().unwrap()], + methods: russh::MethodSet::NONE, + ..Default::default() + }); + let handler = NoneOnlyTestServer { + none_attempts: server_attempts, + }; + let session = russh::server::run_stream(config, socket, handler) + .await + .unwrap(); + let _ = session.await; + }); + + // The alias does not resolve, so only the proxy can reach the server. + let proxy_command = format!("nc 127.0.0.1 {port}"); + let mut profile = none_auth_config("coder", "coder-workspace.invalid"); + profile.proxy_command = Some(proxy_command.clone()); + let manager = SSHConnectionManager::new(dir.clone()); + manager.save_connection(&profile).await.unwrap(); + + let reloaded = SSHConnectionManager::new(dir.clone()); + reloaded.load_saved_connections().await.unwrap(); + let restored = reloaded + .load_connection_config_from_saved("coder") + .await + .unwrap() + .unwrap(); + assert!(matches!(restored.auth, SSHAuthMethod::None)); + assert_eq!(restored.proxy_command, Some(proxy_command)); + + let result = reloaded.connect(restored).await.unwrap(); + assert!(result.success, "unexpected result: {:?}", result.error); + assert!(none_attempts.load(Ordering::SeqCst) >= 1); + + let _ = reloaded.disconnect("coder").await; + server.abort(); + let _ = tokio::fs::remove_dir_all(&dir).await; + } + + /// `authType` exactly as released builds parse it: no `None` variant. + #[derive(Debug, serde::Deserialize, serde::Serialize)] + #[serde(tag = "type")] + enum ReleasedSavedAuthType { + Password, + PrivateKey { + #[serde(rename = "keyPath")] + key_path: String, + }, + Agent, + KeyboardInteractive, + } + + #[derive(Debug, serde::Deserialize, serde::Serialize)] + #[serde(rename_all = "camelCase")] + struct ReleasedSavedConnection { + id: String, + name: String, + host: String, + port: u16, + username: String, + auth_type: ReleasedSavedAuthType, + } + + fn released_profile(id: &str) -> serde_json::Value { + serde_json::json!({ + "id": id, + "name": id, + "host": format!("{id}.test"), + "port": 22, + "username": "dev", + "authType": { "type": "PrivateKey", "keyPath": "~/.ssh/id_rsa" }, + }) + } + + fn none_auth_config(id: &str, host: &str) -> SSHConnectionConfig { + SSHConnectionConfig { + id: id.to_string(), + name: "coder agent".to_string(), + host: host.to_string(), + port: 2222, + username: "coder".to_string(), + auth: SSHAuthMethod::None, + default_workspace: Some("/root".to_string()), + proxy_jump: None, + proxy_command: None, + container: None, + wsl: None, + options: Default::default(), + } + } + + #[tokio::test] + async fn none_auth_profile_survives_a_released_reader_save_and_upgrade() { + let dir = test_data_dir("none-auth-downgrade"); + tokio::fs::create_dir_all(&dir).await.unwrap(); + let primary_path = dir.join("ssh_connections.json"); + tokio::fs::write( + &primary_path, + serde_json::to_vec(&vec![released_profile("old-a")]).unwrap(), + ) + .await + .unwrap(); + + let upgraded = SSHConnectionManager::new(dir.clone()); + upgraded.load_saved_connections().await.unwrap(); + upgraded + .save_connection(&none_auth_config("coder", "coder.test")) + .await + .unwrap(); + + // Downgrade: a released build parses the whole list, then rewrites it + // from memory after the user adds a profile. + let content = tokio::fs::read_to_string(&primary_path).await.unwrap(); + let mut released: Vec = serde_json::from_str(&content) + .expect("released builds must keep parsing the primary file"); + assert_eq!(released.len(), 1); + released.push(serde_json::from_value(released_profile("old-b")).unwrap()); + tokio::fs::write(&primary_path, serde_json::to_vec(&released).unwrap()) + .await + .unwrap(); + + // Upgrade again: nothing either side wrote is lost. + let reupgraded = SSHConnectionManager::new(dir.clone()); + reupgraded.load_saved_connections().await.unwrap(); + let mut ids: Vec = reupgraded + .get_saved_connections() + .await + .into_iter() + .map(|connection| connection.id) + .collect(); + ids.sort(); + assert_eq!(ids, ["coder", "old-a", "old-b"]); + let restored = reupgraded + .load_connection_config_from_saved("coder") + .await + .unwrap() + .unwrap(); + assert!(matches!(restored.auth, SSHAuthMethod::None)); + let _ = tokio::fs::remove_dir_all(&dir).await; + } + + #[tokio::test] + async fn none_profiles_keep_port_scoped_ids_and_legacy_alias_dedup_across_stores() { + let dir = test_data_dir("none-auth-port-ids"); + tokio::fs::create_dir_all(&dir).await.unwrap(); + let manager = SSHConnectionManager::new(dir.clone()); + let mut key_profile = none_auth_config("ssh-coder@ws", "ws"); + key_profile.port = 22; + key_profile.auth = SSHAuthMethod::Agent { + key_fingerprint: None, + fallback_key_path: None, + }; + manager.save_connection(&key_profile).await.unwrap(); + let mut scoped = none_auth_config("ssh-coder@ws#2222", "ws"); + scoped.port = 2222; + manager.save_connection(&scoped).await.unwrap(); + + // Two ports on one host stay distinct even though they live in + // different stores. + let reloaded = SSHConnectionManager::new(dir.clone()); + reloaded.load_saved_connections().await.unwrap(); + let mut saved: Vec<(String, u16)> = reloaded + .get_saved_connections() + .await + .into_iter() + .map(|c| (c.id, c.port)) + .collect(); + saved.sort(); + assert_eq!( + saved, + vec![ + ("ssh-coder@ws".to_string(), 22), + ("ssh-coder@ws#2222".to_string(), 2222), + ] + ); + let restored = reloaded + .load_connection_config_from_saved("ssh-coder@ws#2222") + .await + .unwrap() + .unwrap(); + assert!(matches!(restored.auth, SSHAuthMethod::None)); + + // A legacy `:port` alias of the key profile switched to `None` + // replaces it and moves it to the extended store. + let mut alias = none_auth_config("ssh-coder@ws:22", "ws"); + alias.port = 22; + reloaded.save_connection(&alias).await.unwrap(); + let primary = tokio::fs::read_to_string(dir.join("ssh_connections.json")) + .await + .unwrap(); + assert!( + serde_json::from_str::>(&primary) + .unwrap() + .is_empty() + ); + let reloaded = SSHConnectionManager::new(dir.clone()); + reloaded.load_saved_connections().await.unwrap(); + let mut ids: Vec = reloaded + .get_saved_connections() + .await + .into_iter() + .map(|c| c.id) + .collect(); + ids.sort(); + assert_eq!(ids, ["ssh-coder@ws#2222", "ssh-coder@ws:22"]); + let _ = tokio::fs::remove_dir_all(&dir).await; + } + + #[tokio::test] + async fn primary_alias_from_an_older_build_shadows_the_same_extended_endpoint() { + let dir = test_data_dir("none-auth-alias-shadow"); + tokio::fs::create_dir_all(&dir).await.unwrap(); + let manager = SSHConnectionManager::new(dir.clone()); + let mut none_profile = none_auth_config("ssh-coder@ws", "ws"); + none_profile.port = 22; + manager.save_connection(&none_profile).await.unwrap(); + let mut alias = released_profile("ssh-coder@ws:22"); + alias["host"] = serde_json::json!("ws"); + alias["username"] = serde_json::json!("coder"); + let mut other_port = released_profile("ssh-coder@ws:2201"); + other_port["host"] = serde_json::json!("ws"); + other_port["username"] = serde_json::json!("coder"); + other_port["port"] = serde_json::json!(2201); + tokio::fs::write( + dir.join("ssh_connections.json"), + serde_json::to_vec(&vec![alias, other_port]).unwrap(), + ) + .await + .unwrap(); + + let reloaded = SSHConnectionManager::new(dir.clone()); + reloaded.load_saved_connections().await.unwrap(); + let mut ids: Vec = reloaded + .get_saved_connections() + .await + .into_iter() + .map(|c| c.id) + .collect(); + ids.sort(); + assert_eq!(ids, ["ssh-coder@ws:22", "ssh-coder@ws:2201"]); + let _ = tokio::fs::remove_dir_all(&dir).await; + } + + #[tokio::test] + async fn none_profile_in_the_primary_file_moves_to_the_extended_store() { + let dir = test_data_dir("none-auth-relocate"); + tokio::fs::create_dir_all(&dir).await.unwrap(); + let primary_path = dir.join("ssh_connections.json"); + let mut none_profile = released_profile("coder"); + none_profile["authType"] = serde_json::json!({ "type": "None" }); + tokio::fs::write( + &primary_path, + serde_json::to_vec(&vec![released_profile("old-a"), none_profile]).unwrap(), + ) + .await + .unwrap(); + + let manager = SSHConnectionManager::new(dir.clone()); + manager.load_saved_connections().await.unwrap(); + assert_eq!(manager.get_saved_connections().await.len(), 2); + manager.delete_saved_connection("old-a").await.unwrap(); + + let content = tokio::fs::read_to_string(&primary_path).await.unwrap(); + serde_json::from_str::>(&content) + .expect("a saved primary file must stay readable by released builds"); + let extended = tokio::fs::read_to_string(dir.join(EXTENDED_SAVED_CONNECTIONS_FILE)) + .await + .unwrap(); + assert!(extended.contains("\"coder\"")); + let _ = tokio::fs::remove_dir_all(&dir).await; + } + + #[tokio::test] + async fn changing_auth_moves_a_profile_between_stores_and_delete_clears_it() { + let dir = test_data_dir("none-auth-switch"); + tokio::fs::create_dir_all(&dir).await.unwrap(); + let manager = SSHConnectionManager::new(dir.clone()); + manager + .save_connection(&none_auth_config("coder", "coder.test")) + .await + .unwrap(); + let mut with_key = none_auth_config("coder", "coder.test"); + with_key.auth = SSHAuthMethod::Agent { + key_fingerprint: None, + fallback_key_path: None, + }; + manager.save_connection(&with_key).await.unwrap(); + + let reloaded = SSHConnectionManager::new(dir.clone()); + reloaded.load_saved_connections().await.unwrap(); + let saved = reloaded.get_saved_connections().await; + assert_eq!(saved.len(), 1); + assert!(!matches!( + saved[0].auth_type, + crate::remote_ssh::types::SavedAuthType::None + )); + + reloaded + .save_connection(&none_auth_config("coder", "coder.test")) + .await + .unwrap(); + reloaded.delete_saved_connection("coder").await.unwrap(); + let reloaded = SSHConnectionManager::new(dir.clone()); + reloaded.load_saved_connections().await.unwrap(); + assert!(reloaded.get_saved_connections().await.is_empty()); + let _ = tokio::fs::remove_dir_all(&dir).await; + } + + #[tokio::test] + async fn primary_profile_recreated_by_an_older_build_shadows_the_extended_one() { + let dir = test_data_dir("none-auth-shadow"); + tokio::fs::create_dir_all(&dir).await.unwrap(); + let manager = SSHConnectionManager::new(dir.clone()); + manager + .save_connection(&none_auth_config("coder", "coder.test")) + .await + .unwrap(); + tokio::fs::write( + dir.join("ssh_connections.json"), + serde_json::to_vec(&vec![released_profile("coder")]).unwrap(), + ) + .await + .unwrap(); + + let reloaded = SSHConnectionManager::new(dir.clone()); + reloaded.load_saved_connections().await.unwrap(); + let saved = reloaded.get_saved_connections().await; + assert_eq!(saved.len(), 1); + assert!(matches!( + saved[0].auth_type, + crate::remote_ssh::types::SavedAuthType::PrivateKey { .. } + )); + let _ = tokio::fs::remove_dir_all(&dir).await; + } + + #[tokio::test] + async fn unreadable_extended_store_is_kept_aside_and_never_blocks_primary_profiles() { + let dir = test_data_dir("none-auth-unreadable"); + tokio::fs::create_dir_all(&dir).await.unwrap(); + tokio::fs::write( + dir.join("ssh_connections.json"), + serde_json::to_vec(&vec![released_profile("old-a")]).unwrap(), + ) + .await + .unwrap(); + let extended_path = dir.join(EXTENDED_SAVED_CONNECTIONS_FILE); + tokio::fs::write(&extended_path, "not json").await.unwrap(); + + let manager = SSHConnectionManager::new(dir.clone()); + manager.load_saved_connections().await.unwrap(); + assert_eq!(manager.get_saved_connections().await.len(), 1); + manager + .save_connection(&none_auth_config("coder", "coder.test")) + .await + .unwrap(); + + let backup = tokio::fs::read_to_string(extended_path.with_extension("json.unreadable")) + .await + .unwrap(); + assert_eq!(backup, "not json"); + let _ = tokio::fs::remove_dir_all(&dir).await; + } + + #[tokio::test] + async fn unreadable_primary_file_keeps_extended_profiles_for_the_next_save() { + let dir = test_data_dir("none-auth-primary-corrupt"); + tokio::fs::create_dir_all(&dir).await.unwrap(); + let manager = SSHConnectionManager::new(dir.clone()); + manager + .save_connection(&none_auth_config("coder", "coder.test")) + .await + .unwrap(); + tokio::fs::write(dir.join("ssh_connections.json"), "not json") + .await + .unwrap(); + + let reloaded = SSHConnectionManager::new(dir.clone()); + assert!(reloaded.load_saved_connections().await.is_err()); + assert_eq!(reloaded.get_saved_connections().await.len(), 1); + let _ = tokio::fs::remove_dir_all(&dir).await; + } + #[tokio::test] async fn prunes_remote_workspaces_without_saved_connection() { let dir = test_data_dir("missing-saved"); diff --git a/src/crates/services/services-integrations/src/remote_ssh/types.rs b/src/crates/services/services-integrations/src/remote_ssh/types.rs index 0a965352f5..998bc3ccb1 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/types.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/types.rs @@ -117,7 +117,8 @@ impl SSHAuthMethod { fn connection_params_equal(&self, other: &Self) -> bool { match (self, other) { (Self::Password { .. }, Self::Password { .. }) - | (Self::KeyboardInteractive { .. }, Self::KeyboardInteractive { .. }) => true, + | (Self::KeyboardInteractive { .. }, Self::KeyboardInteractive { .. }) + | (Self::None, Self::None) => true, ( Self::PrivateKey { key_path, @@ -287,6 +288,14 @@ pub enum SSHAuthMethod { #[serde(default)] responses: Vec, }, + /// Accept the server without sending credentials (`none` method). + /// + /// Needed for endpoints whose transport is already authenticated and that + /// therefore advertise only `none`: Coder workspace agents are the motivating + /// case, because `coder ssh --stdio` authenticates the tunnel with the CLI + /// token and the agent disconnects clients that attempt public key or password + /// authentication. + None, } fn deserialize_ssh_auth_method<'de, D>(deserializer: D) -> Result @@ -316,6 +325,7 @@ where #[serde(default)] responses: Vec, }, + None, } match Helper::deserialize(deserializer)? { Helper::Password { password } => Ok(SSHAuthMethod::Password { password }), @@ -338,6 +348,7 @@ where Helper::KeyboardInteractive { responses } => { Ok(SSHAuthMethod::KeyboardInteractive { responses }) } + Helper::None => Ok(SSHAuthMethod::None), } } @@ -399,6 +410,8 @@ pub enum SavedAuthType { fallback_key_path: Option, }, KeyboardInteractive, + /// Server accepts the connection without credentials (see `SSHAuthMethod::None`). + None, } fn deserialize_saved_auth_type<'de, D>(deserializer: D) -> Result @@ -422,6 +435,7 @@ where fallback_key_path: Option, }, KeyboardInteractive, + None, } match Helper::deserialize(deserializer)? { Helper::Password => Ok(SavedAuthType::Password), @@ -440,6 +454,7 @@ where fallback_key_path: fallback_key_path.or_else(|| Some("~/.ssh/id_rsa".to_string())), }), Helper::KeyboardInteractive => Ok(SavedAuthType::KeyboardInteractive), + Helper::None => Ok(SavedAuthType::None), } } diff --git a/src/web-ui/src/app/components/NavPanel/MainNav.tsx b/src/web-ui/src/app/components/NavPanel/MainNav.tsx index 8d4607b681..f0de86d6ed 100644 --- a/src/web-ui/src/app/components/NavPanel/MainNav.tsx +++ b/src/web-ui/src/app/components/NavPanel/MainNav.tsx @@ -39,7 +39,7 @@ import { isRemoteWorkspace } from '@/shared/types'; import { useSSHRemoteContext, SSHConnectionDialog, RemoteFileBrowser } from '@/features/ssh-remote'; import { savedConnectionConfig } from '@/features/ssh-remote/savedConnectionConfig'; import { workspacePresetHost } from '@/features/ssh-remote/useWorkspaceSourceOptions'; -import { isSshAuthenticationError, workspaceSourceErrorKey } from '@/features/ssh-remote/workspaceSourceError'; +import { canRepairSshCredentials, sshConnectionErrorKey, workspaceSourceErrorKey } from '@/features/ssh-remote/workspaceSourceError'; import type { WorkspaceConnectionTarget } from '@/features/ssh-remote/types'; import { openGlobalSearch } from '@/app/global-search/globalSearchStore'; import { useSidebarNavigation } from '@/app/navigation/useSidebarNavigation'; @@ -125,9 +125,9 @@ const MainNav: React.FC = () => { return { connectionId: result?.connectionId || profile.id, connectionName: profile.name, sshHost: profile.host }; } catch (cause) { scope.assertCurrent('retry project source authentication'); - if (profile.wsl || profile.container?.local || !isSshAuthenticationError(cause)) { + if (profile.wsl || profile.container?.local || !canRepairSshCredentials(profile.authType, cause)) { log.error('Failed to connect selected project source', cause); - throw new Error(t(profile.wsl || profile.container?.local ? workspaceSourceErrorKey(target, cause) : 'workspaceSource.connectionFailed')); + throw new Error(t(profile.wsl || profile.container?.local ? workspaceSourceErrorKey(target, cause) : sshConnectionErrorKey(cause))); } preset = { kind: 'saved', connection: profile, authenticate: true }; } diff --git a/src/web-ui/src/features/ssh-remote/SSHConnectionDialog.fields.test.tsx b/src/web-ui/src/features/ssh-remote/SSHConnectionDialog.fields.test.tsx index c69d3bf725..12ebe7c496 100644 --- a/src/web-ui/src/features/ssh-remote/SSHConnectionDialog.fields.test.tsx +++ b/src/web-ui/src/features/ssh-remote/SSHConnectionDialog.fields.test.tsx @@ -11,7 +11,8 @@ vi.mock('@/infrastructure/api/service-api/RemoteConnectAPI', async importOrigina ...await importOriginal(), remoteConnectAPI: { getDeviceInfo: async () => ({ device_id: 'local', device_name: 'Workstation' }) }, })); -const { sshApi, remote } = vi.hoisted(() => ({ +const { sshApi, remote, peerDevice } = vi.hoisted(() => ({ + peerDevice: { value: null as null | { peerMode: { active: boolean; deviceName: string }; currentPeerCapabilities: object | null } }, sshApi: { listSavedConnections: vi.fn(), listSSHConfigHosts: vi.fn(), getSSHConfig: vi.fn(), listWslDistributions: vi.fn(), listDockerContainers: vi.fn(), saveConnection: vi.fn(), @@ -23,6 +24,10 @@ vi.mock('@/infrastructure/i18n', () => { return { useI18n: () => ({ t }) }; }); vi.mock('./SSHRemoteContext', () => ({ useSSHRemoteContext: () => remote })); +vi.mock('@/infrastructure/peer-device/peerDeviceContextState', async importOriginal => ({ + ...await importOriginal(), + usePeerDeviceModeOptional: () => peerDevice.value, +})); vi.mock('./sshApi', () => ({ sshApi })); vi.mock('./pickSshPrivateKeyPath', () => ({ pickSshPrivateKeyPath: vi.fn(), pickSshCertificatePath: vi.fn() })); @@ -60,6 +65,7 @@ describe('remote workspace form composition', () => { beforeEach(() => { vi.clearAllMocks(); + peerDevice.value = null; Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', { configurable: true, value: vi.fn() }); sshApi.listSavedConnections.mockResolvedValue([]); sshApi.listSSHConfigHosts.mockResolvedValue([]); @@ -254,6 +260,79 @@ describe('remote workspace form composition', () => { auth: { type: 'PrivateKey', keyPath: '/keys/build' }, proxyJump: 'jump.test', container: expect.objectContaining({ name: 'devbox', local: false }) }), { browseAfterConnect: true }); }); + it('connects a none-authenticated endpoint without asking for credentials', async () => { + remote.connect.mockResolvedValue(undefined); + sshApi.listSavedConnections.mockResolvedValue([{ + id: 'saved', name: 'Saved', host: 'saved.test', port: 22, username: 'dev', authType: { type: 'Password' }, + }]); + await renderConnection('ssh', true); + const newTab = document.querySelector('[role="tab"][data-openbitfun-value="new"]')!; + await act(async () => newTab.click()); + enterValue(fieldControl('ssh.remote.host') as HTMLInputElement, '127.0.0.1'); + enterValue(fieldControl('ssh.remote.username') as HTMLInputElement, 'coder'); + // The default method asks for a password; switching to none must drop it. + expect(document.querySelector('input[type="password"]')).not.toBeNull(); + + await act(async () => fieldControl('ssh.remote.authMethod').click()); + const option = [...document.querySelectorAll('[data-openbitfun-listbox-option]')] + .find(item => item.textContent === 'ssh.remote.noAuth')!; + expect(option).toBeDefined(); + await act(async () => option.click()); + + expect(document.body.textContent).toContain('ssh.remote.noAuthHint'); + expect(document.querySelector('input[type="password"]')).toBeNull(); + + await act(async () => [...document.querySelectorAll('footer button')] + .find(button => button.textContent === 'ssh.remote.connect')!.click()); + expect(remote.connect).toHaveBeenCalledWith( + 'ssh-coder@127.0.0.1', + expect.objectContaining({ + host: '127.0.0.1', + username: 'coder', + auth: { type: 'None' }, + }), + { browseAfterConnect: true }, + ); + }); + + it('offers none authentication on a peer surface only after the host negotiated it', async () => { + const authOptionLabels = async () => { + await renderConnection('ssh', true); + await act(async () => fieldControl('ssh.remote.authMethod').click()); + const labels = [...document.querySelectorAll('[data-openbitfun-listbox-option]')].map(item => item.textContent); + await act(async () => fieldControl('ssh.remote.authMethod').click()); + return labels; + }; + peerDevice.value = { peerMode: { active: true, deviceName: 'Older peer' }, currentPeerCapabilities: { sshNoneAuthV1: false } }; + expect(await authOptionLabels()).not.toContain('ssh.remote.noAuth'); + peerDevice.value = { peerMode: { active: true, deviceName: 'Peer' }, currentPeerCapabilities: { sshNoneAuthV1: true } }; + expect(await authOptionLabels()).toContain('ssh.remote.noAuth'); + }); + + it('reports a rejected none profile without falling back to a credentials prompt', async () => { + sshApi.listSavedConnections.mockResolvedValue([{ + id: 'coder', name: 'Coder', host: 'coder.test', port: 22, username: 'coder', authType: { type: 'None' }, + }]); + remote.connect.mockRejectedValue(new Error('SSH authentication was rejected for user coder')); + await renderConnection('ssh', true); + await act(async () => document.querySelector('[data-openbitfun-part="connectionList"] button[aria-pressed]')!.click()); + await act(async () => [...document.querySelectorAll('footer button')].find(item => item.textContent === 'ssh.remote.connect')!.click()); + expect(remote.connect).toHaveBeenCalledWith('coder', expect.objectContaining({ auth: { type: 'None' } }), expect.anything()); + expect(document.querySelector('input[type="password"]')).toBeNull(); + expect(document.body.textContent).toContain('workspaceSource.connectionFailed'); + }); + + it('asks to update an older host instead of showing a generic failure for a none profile', async () => { + sshApi.listSavedConnections.mockResolvedValue([{ + id: 'coder', name: 'Coder', host: 'coder.test', port: 22, username: 'coder', authType: { type: 'None' }, + }]); + remote.connect.mockRejectedValue(new Error('ssh_none_auth_v1_unsupported: The connected Peer host does not support it')); + await renderConnection('ssh', true); + await act(async () => document.querySelector('[data-openbitfun-part="connectionList"] button[aria-pressed]')!.click()); + await act(async () => [...document.querySelectorAll('footer button')].find(item => item.textContent === 'ssh.remote.connect')!.click()); + expect(document.body.textContent).toContain('ssh.remote.noAuthUnsupported'); + }); + it('requires an existing SSH host before configuring a remote container', async () => { await renderConnection('remoteDocker', true); expect(document.body.textContent).toContain('workspaceSource.existingHostRequired'); diff --git a/src/web-ui/src/features/ssh-remote/SSHConnectionDialog.tsx b/src/web-ui/src/features/ssh-remote/SSHConnectionDialog.tsx index 5702f4e6c6..acd4c77c28 100644 --- a/src/web-ui/src/features/ssh-remote/SSHConnectionDialog.tsx +++ b/src/web-ui/src/features/ssh-remote/SSHConnectionDialog.tsx @@ -32,10 +32,11 @@ import { OverflowText, import React, { useState, useEffect, useCallback, useRef, useId, useSyncExternalStore } from 'react'; import { useI18n } from '@/infrastructure/i18n'; import { usePeerDeviceModeOptional } from '@/infrastructure/peer-device/peerDeviceContextState'; +import { canUseSshNoneAuthOnSurface } from '@/infrastructure/peer-device/peerCapabilityResolution'; import { getActiveSurfaceScope, onSurfaceActivated } from '@/infrastructure/peer-device/deviceSurface'; import { useSSHRemoteContext } from './SSHRemoteContext'; import { SSHAuthPromptDialog, type SSHAuthPromptSubmitPayload } from './SSHAuthPromptDialog'; -import { EyeOff, FolderOpen, Key, Loader2, Lock, Server } from 'lucide-react'; +import { EyeOff, FolderOpen, Key, Loader2, Lock, Server, Unlock } from 'lucide-react'; import type { ConnectionTestReport, ConnectionTestStage, @@ -50,7 +51,7 @@ import type { import { sshApi } from './sshApi'; import { WorkspaceSourceSelector } from './WorkspaceSourceSelector'; import { WorkspaceChoiceCapsules } from './WorkspaceChoiceCapsules'; -import { workspaceSourceErrorKey, isSshAuthenticationError } from './workspaceSourceError'; +import { canRepairSshCredentials, sshConnectionErrorKey, workspaceSourceErrorKey } from './workspaceSourceError'; import { savedConnectionConfig } from './savedConnectionConfig'; import type { WorkspaceConnectionPreset } from './useWorkspaceSourceOptions'; import { sameWorkspaceSource, savedConnectionTarget } from './workspaceSource'; @@ -76,7 +77,7 @@ interface SSHConnectionDialogProps { const emptySshEndpoint = () => ({ host: '', port: '22', username: '', - authType: 'password' as 'password' | 'privateKey' | 'agent' | 'keyboardInteractive', + authType: 'password' as 'password' | 'privateKey' | 'agent' | 'keyboardInteractive' | 'none', password: '', keyPath: '~/.ssh/id_rsa', passphrase: '', certificatePath: '', keyFingerprint: '', fallbackKeyPath: '~/.ssh/id_rsa', verificationCode: '', proxyJump: '', }); @@ -95,6 +96,7 @@ export const SSHConnectionDialog: React.FC = ({ }) => { const { t } = useI18n('common'); const peer = usePeerDeviceModeOptional(); + const noAuthSupported = canUseSshNoneAuthOnSurface(Boolean(peer?.peerMode.active), peer?.currentPeerCapabilities ?? null); const scope = useSyncExternalStore(onSurfaceActivated, getActiveSurfaceScope, getActiveSurfaceScope); const { connect, status, connectionError, clearError } = useSSHRemoteContext(); const [savedConnections, setSavedConnections] = useState([]); @@ -385,6 +387,8 @@ export const SSHConnectionDialog: React.FC = ({ type: 'KeyboardInteractive', responses: [formData.password, formData.verificationCode].filter(Boolean), }; + case 'none': + return { type: 'None' }; } }; @@ -449,6 +453,10 @@ export const SSHConnectionDialog: React.FC = ({ setLocalError(t('ssh.remote.passwordRequired')); return null; } + if (!isLocalDocker && formData.authType === 'none' && !noAuthSupported) { + setLocalError(t('ssh.remote.noAuthUnsupported')); + return null; + } if (!isLocalDocker && formData.authType === 'privateKey' && !formData.keyPath.trim()) { setLocalError(t('ssh.remote.keyPathRequired')); return null; @@ -544,6 +552,7 @@ export const SSHConnectionDialog: React.FC = ({ : buildAuthMethod(), defaultWorkspace: editingProfile?.defaultWorkspace, proxyJump: !isLocalDocker ? resolvedProxyJump || undefined : undefined, + proxyCommand: editingProfile?.proxyCommand, container: usesContainer ? { name: containerName, access: formData.targetType === 'containerSshd' @@ -574,14 +583,14 @@ export const SSHConnectionDialog: React.FC = ({ const config = await buildConnectionConfig(true); if (!config) return; try { await connectAndFinish(config); } catch (cause) { - if (inheritedHost && isSshAuthenticationError(cause)) { + if (inheritedHost && canRepairSshCredentials(config.auth, cause)) { const { auth, ...profile } = config; setCredentialsPrompt({ ...profile, authType: auth.type === 'Password' ? { type: 'Password' } : auth.type === 'KeyboardInteractive' ? { type: 'KeyboardInteractive' } : auth }); } else throw cause; } } catch (e) { - setLocalError(t(isLocalProcessTarget || inheritedHost ? workspaceSourceErrorKey(formData.targetType, e) : 'workspaceSource.connectionFailed')); + setLocalError(t(isLocalProcessTarget || inheritedHost ? workspaceSourceErrorKey(formData.targetType, e) : sshConnectionErrorKey(e))); } finally { setIsConnecting(false); } @@ -656,8 +665,8 @@ export const SSHConnectionDialog: React.FC = ({ // environment-specific status instead of asking for SSH credentials. if (conn.wsl || conn.container?.local) { setLocalError(t(workspaceSourceErrorKey(savedConnectionTarget(conn), error))); - } else if (isSshAuthenticationError(error)) setCredentialsPrompt(conn); - else setLocalError(t('workspaceSource.connectionFailed')); + } else if (canRepairSshCredentials(conn.authType, error)) setCredentialsPrompt(conn); + else setLocalError(t(sshConnectionErrorKey(error))); }, [t]); const handleQuickConnect = useCallback(async (conn: SavedConnection) => { @@ -755,7 +764,9 @@ export const SSHConnectionDialog: React.FC = ({ ? 'privateKey' : conn.authType.type === 'Agent' ? 'agent' - : 'keyboardInteractive'; + : conn.authType.type === 'KeyboardInteractive' + ? 'keyboardInteractive' + : 'none'; const targetType = savedConnectionTarget(conn); setFormData({ targetType, @@ -828,6 +839,10 @@ export const SSHConnectionDialog: React.FC = ({ value: 'keyboardInteractive', icon: , }, + // A saved `none` profile stays visible so its method is not silently rewritten. + ...(noAuthSupported || formData.authType === 'none' + ? [{ label: t('ssh.remote.noAuth'), value: 'none', icon: }] + : []), ]; const containerAccessOptions = [ { label: t('ssh.remote.containerAccessAuto'), value: 'auto' }, @@ -1177,6 +1192,9 @@ export const SSHConnectionDialog: React.FC = ({ size="md" /> + {formData.authType === 'none' && ( +
{t('ssh.remote.noAuthHint')}
+ )} {/* Password */} diff --git a/src/web-ui/src/features/ssh-remote/SSHRemoteProvider.test.tsx b/src/web-ui/src/features/ssh-remote/SSHRemoteProvider.test.tsx index 276bd73617..90baf6f382 100644 --- a/src/web-ui/src/features/ssh-remote/SSHRemoteProvider.test.tsx +++ b/src/web-ui/src/features/ssh-remote/SSHRemoteProvider.test.tsx @@ -381,6 +381,48 @@ describe('SSHRemoteProvider startup restore', () => { ); }); + it('restores a none-authenticated workspace without inventing credentials', async () => { + const remoteWorkspace = { + id: 'ws-coder-1', + name: 'repos', + rootPath: '/root/repos', + workspaceType: WorkspaceType.SingleProject, + workspaceKind: WorkspaceKind.Remote, + languages: [] as string[], + openedAt: new Date().toISOString(), + lastAccessed: new Date().toISOString(), + tags: [] as string[], + connectionId: 'conn-coder', + connectionName: 'coder-agent', + sshHost: '127.0.0.1', + }; + workspaceManagerMock.getState.mockReturnValue({ + loading: false, + openedWorkspaces: new Map([[remoteWorkspace.id, remoteWorkspace]]), + activeWorkspaceId: remoteWorkspace.id, + }); + sshApiMock.listSavedConnections.mockResolvedValue([ + { + id: 'conn-coder', + name: 'coder-agent', + host: '127.0.0.1', + port: 2222, + username: 'coder', + authType: { type: 'None' }, + proxyCommand: 'coder ssh --stdio repos', + }, + ]); + sshApiMock.connect.mockResolvedValue({ success: true, connectionId: 'conn-coder' }); + + await renderProvider(); + + expect(sshApiMock.connect).toHaveBeenCalledWith( + expect.objectContaining({ auth: { type: 'None' }, proxyCommand: 'coder ssh --stdio repos' }) + ); + expect(sshApiMock.hasStoredPassword).not.toHaveBeenCalled(); + expect(sshApiMock.openWorkspace).toHaveBeenCalledWith('conn-coder', '/root/repos'); + }); + it('keeps workspace restore metadata when its saved connection is unavailable', async () => { const remoteWorkspace = { id: 'ws-orphaned-1', diff --git a/src/web-ui/src/features/ssh-remote/SSHRemoteProvider.tsx b/src/web-ui/src/features/ssh-remote/SSHRemoteProvider.tsx index b67a66f5fd..2a89834158 100644 --- a/src/web-ui/src/features/ssh-remote/SSHRemoteProvider.tsx +++ b/src/web-ui/src/features/ssh-remote/SSHRemoteProvider.tsx @@ -385,6 +385,9 @@ export const SSHRemoteProvider: React.FC = ({ children } }; } else if (savedConn.authType.type === 'KeyboardInteractive') { return false; + } else if (savedConn.authType.type === 'None') { + // Nothing to supply: the endpoint authenticates the transport for us. + authMethod = { type: 'None' }; } else { // Caller must only invoke password reconnect when vault has a password (see checkRemoteWorkspace). authMethod = { type: 'Password', password: '' }; @@ -399,6 +402,7 @@ export const SSHRemoteProvider: React.FC = ({ children } auth: authMethod, defaultWorkspace: savedConn.defaultWorkspace, proxyJump: savedConn.proxyJump, + proxyCommand: savedConn.proxyCommand, container: savedConn.container, wsl: savedConn.wsl, options: savedConn.options, diff --git a/src/web-ui/src/features/ssh-remote/types.ts b/src/web-ui/src/features/ssh-remote/types.ts index af1f0ea9ed..5b92f39caa 100644 --- a/src/web-ui/src/features/ssh-remote/types.ts +++ b/src/web-ui/src/features/ssh-remote/types.ts @@ -13,6 +13,8 @@ export interface SSHConnectionConfig { auth: SSHAuthMethod; defaultWorkspace?: string; proxyJump?: string; + /** Host-owned value carried through unchanged; no form edits it yet. */ + proxyCommand?: string; container?: ContainerWorkspaceConfig; wsl?: WslWorkspaceConfig; options?: SSHConnectionOptions; @@ -41,13 +43,16 @@ export type SSHAuthMethod = | { type: 'Password'; password: string } | { type: 'PrivateKey'; keyPath: string; passphrase?: string; certificatePath?: string } | { type: 'Agent'; keyFingerprint?: string; fallbackKeyPath?: string } - | { type: 'KeyboardInteractive'; responses: string[] }; + | { type: 'KeyboardInteractive'; responses: string[] } + /** Server accepts the connection without credentials (already-authenticated tunnels). */ + | { type: 'None' }; export type SavedAuthType = | { type: 'Password' } | { type: 'PrivateKey'; keyPath: string; certificatePath?: string } | { type: 'Agent'; keyFingerprint?: string; fallbackKeyPath?: string } - | { type: 'KeyboardInteractive' }; + | { type: 'KeyboardInteractive' } + | { type: 'None' }; export interface SavedConnection { id: string; @@ -59,6 +64,7 @@ export interface SavedConnection { defaultWorkspace?: string; lastConnected?: number; proxyJump?: string; + proxyCommand?: string; container?: ContainerWorkspaceConfig; wsl?: WslWorkspaceConfig; options?: SSHConnectionOptions; diff --git a/src/web-ui/src/features/ssh-remote/workspaceSourceError.test.ts b/src/web-ui/src/features/ssh-remote/workspaceSourceError.test.ts index 0f8d6da92c..2d1c5e0dbd 100644 --- a/src/web-ui/src/features/ssh-remote/workspaceSourceError.test.ts +++ b/src/web-ui/src/features/ssh-remote/workspaceSourceError.test.ts @@ -1,5 +1,5 @@ import { expect, it } from 'vitest'; -import { isSshAuthenticationError, workspaceSourceErrorKey } from './workspaceSourceError'; +import { canRepairSshCredentials, isSshAuthenticationError, sshConnectionErrorKey, workspaceSourceErrorKey } from './workspaceSourceError'; it.each([ ["Error: Failed to start local Docker executable 'docker'", 'workspaceSource.dockerUnavailable'], @@ -17,3 +17,14 @@ it('requests credentials for authentication failures rather than network or nati expect(isSshAuthenticationError(new Error('connection refused'))).toBe(false); expect(isSshAuthenticationError(new Error("Failed to start local Docker executable 'docker'"))).toBe(false); }); + +it('never repairs a none profile with credentials', () => { + const rejected = new Error('authentication was rejected'); + expect(canRepairSshCredentials({ type: 'Password' }, rejected)).toBe(true); + expect(canRepairSshCredentials({ type: 'None' }, rejected)).toBe(false); +}); + +it('names the host update for an unsupported none profile', () => { + expect(sshConnectionErrorKey(new Error('ssh_none_auth_v1_unsupported: update the host'))).toBe('ssh.remote.noAuthUnsupported'); + expect(sshConnectionErrorKey(new Error('connection refused'))).toBe('workspaceSource.connectionFailed'); +}); diff --git a/src/web-ui/src/features/ssh-remote/workspaceSourceError.ts b/src/web-ui/src/features/ssh-remote/workspaceSourceError.ts index 2c3f1ce5ff..798976b844 100644 --- a/src/web-ui/src/features/ssh-remote/workspaceSourceError.ts +++ b/src/web-ui/src/features/ssh-remote/workspaceSourceError.ts @@ -18,3 +18,15 @@ export function workspaceSourceErrorKey(source: WorkspaceSource, error: unknown) export function isSshAuthenticationError(error: unknown) { return /credentials required|authenticat|password|passphrase|private key|publickey|keyboard.interactive|challenge response|ssh agent/i.test(String(error)); } + +/** `None` profiles have no credentials to repair; never turn a rejection into a password prompt. */ +export function canRepairSshCredentials(authType: { type: string }, error: unknown) { + return authType.type !== 'None' && isSshAuthenticationError(error); +} + +/** Generic connection failure, except an older host that must be updated to use the profile. */ +export function sshConnectionErrorKey(error: unknown) { + return String(error).includes('ssh_none_auth_v1_unsupported') + ? 'ssh.remote.noAuthUnsupported' + : 'workspaceSource.connectionFailed'; +} diff --git a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts index 175a5ca19a..38fa512f93 100644 --- a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts +++ b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts @@ -686,6 +686,27 @@ describe('PeerDeviceTransportAdapter queue', () => { expect(JSON.stringify(deviceRpc.mock.calls[0])).toContain('Ubuntu'); }); + it.each(['ssh_connect', 'ssh_save_connection', 'ssh_test_connection'])( + 'rejects %s with none authentication before an older peer can fail to parse it', async (command) => { + const deviceRpc = vi.fn(); + const adapter = new PeerDeviceTransportAdapter('peer-1', deviceRpc); + await expect(adapter.request(command, { config: { auth: { type: 'None' } } })) + .rejects.toThrow('ssh_none_auth_v1_unsupported'); + expect(deviceRpc).not.toHaveBeenCalled(); + }, + ); + + it('forwards none authentication to the negotiated host and leaves other methods alone', async () => { + const deviceRpc = vi.fn().mockResolvedValue(JSON.stringify({ resp: 'host_invoke_result', ok: true, value: { success: true } })); + const negotiated = new PeerDeviceTransportAdapter('peer-1', deviceRpc, { supportsSshNoneAuthV1: true }); + await expect(negotiated.request('ssh_connect', { config: { auth: { type: 'None' } } })) + .resolves.toEqual({ success: true }); + const older = new PeerDeviceTransportAdapter('peer-1', deviceRpc); + await expect(older.request('ssh_connect', { config: { auth: { type: 'Agent' } } })) + .resolves.toEqual({ success: true }); + expect(deviceRpc).toHaveBeenCalledTimes(2); + }); + it('forwards MiniApp Agent context files after version negotiation', async () => { const outcome = { sessionId: 'session-1', turnId: 'turn-1' }; const deviceRpc = vi.fn().mockResolvedValue(JSON.stringify({ diff --git a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts index e643fdf832..41751c5dd7 100644 --- a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts +++ b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts @@ -304,6 +304,7 @@ export interface PeerDeviceTransportHooks { /** Enables MiniApp Agent turns carrying inline image attachments. */ supportsMiniAppAgentImagesV1?: boolean; supportsWslWorkspacesV1?: boolean; + supportsSshNoneAuthV1?: boolean; supportsSshPortScopedIdentityV1?: boolean; supportsWholeSessionCopyV1?: boolean; supportsModelRoutingV1?: boolean; @@ -447,6 +448,7 @@ export class PeerDeviceTransportAdapter implements ITransportAdapter { | 'supportsMiniAppAgentContextFilesV1' | 'supportsMiniAppAgentImagesV1' | 'supportsWslWorkspacesV1' + | 'supportsSshNoneAuthV1' | 'supportsSshPortScopedIdentityV1' | 'supportsWholeSessionCopyV1' | 'supportsModelRoutingV1' @@ -573,6 +575,13 @@ export class PeerDeviceTransportAdapter implements ITransportAdapter { ); } + const sshAuthType = (params as { config?: { auth?: { type?: unknown } } } | undefined)?.config?.auth?.type; + if (action.startsWith('ssh_') && sshAuthType === 'None' && this.hooks.supportsSshNoneAuthV1 !== true) { + throw new PeerProductCommandError( + 'ssh_none_auth_v1_unsupported: The connected Peer host does not support SSH connections without authentication; update the executing Desktop host', + ); + } + const sshConfigId = (params as { config?: { id?: unknown } } | undefined)?.config?.id; if ( action.startsWith('ssh_') && diff --git a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts index 771c898d29..458f07abef 100644 --- a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts +++ b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. // Source: openbitfun_product_domains::remote_surface (Product Operation Registry). -export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:feb182159a7e227e" as const; +export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:33ad4ddb17680c30" as const; /** * Registered Tauri commands the Peer Device controller keeps on the controller @@ -212,6 +212,7 @@ export const PEER_HOST_CAPABILITY_IDS = [ "session_trajectory_v1", "user_question_response", "user_question_interaction_v1", + "ssh_none_auth_v1", "terminal_cursor_replay_v1", ] as const; @@ -264,6 +265,7 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< "session_trajectory_v1", "user_question_response", "user_question_interaction_v1", + "ssh_none_auth_v1", ], cli: [ "model_routing_v1", diff --git a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts index 20b7c52e96..dd31900fd1 100644 --- a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts +++ b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts @@ -55,6 +55,7 @@ export interface PeerHostCapabilities { readonly miniAppAgentContextFilesV1: boolean; readonly miniAppAgentImagesV1: boolean; readonly wslWorkspacesV1?: boolean; + readonly sshNoneAuthV1?: boolean; /** Host keeps `ssh-user@host#port` profiles distinct; older hosts get legacy ids only. */ readonly sshPortScopedIdentityV1?: boolean; /** Host stores ordered subscription account pools on model configs. */ @@ -202,6 +203,7 @@ const NO_CAPABILITIES: PeerHostCapabilities = { miniAppAgentContextFilesV1: false, miniAppAgentImagesV1: false, wslWorkspacesV1: false, + sshNoneAuthV1: false, sshPortScopedIdentityV1: false, subscriptionAccountPoolsV1: false, subscriptionQuotaV1: false, @@ -470,6 +472,7 @@ export class PeerConnectionManager { supportsMiniAppAgentContextFilesV1: entry.capabilities.miniAppAgentContextFilesV1, supportsMiniAppAgentImagesV1: entry.capabilities.miniAppAgentImagesV1, supportsWslWorkspacesV1: entry.capabilities.wslWorkspacesV1, + supportsSshNoneAuthV1: entry.capabilities.sshNoneAuthV1, supportsSshPortScopedIdentityV1: entry.capabilities.sshPortScopedIdentityV1, supportsWholeSessionCopyV1: entry.capabilities.wholeSessionCopyV1, supportsModelRoutingV1: entry.capabilities.modelRoutingV1, @@ -566,6 +569,7 @@ export class PeerConnectionManager { miniAppAgentContextFilesV1: caps?.miniapp_agent_context_files_v1 === true, miniAppAgentImagesV1: caps?.miniapp_agent_images_v1 === true, wslWorkspacesV1: caps?.wsl_workspaces_v1 === true, + sshNoneAuthV1: caps?.ssh_none_auth_v1 === true, sshPortScopedIdentityV1: caps?.ssh_port_scoped_identity_v1 === true, subscriptionAccountPoolsV1: caps?.subscription_account_pools_v1 === true, subscriptionQuotaV1: caps?.subscription_quota_v1 === true, @@ -676,6 +680,7 @@ export class PeerConnectionManager { supportsMiniAppAgentContextFilesV1: capabilities.miniAppAgentContextFilesV1, supportsMiniAppAgentImagesV1: capabilities.miniAppAgentImagesV1, supportsWslWorkspacesV1: capabilities.wslWorkspacesV1, + supportsSshNoneAuthV1: capabilities.sshNoneAuthV1, supportsSshPortScopedIdentityV1: capabilities.sshPortScopedIdentityV1, supportsWholeSessionCopyV1: capabilities.wholeSessionCopyV1, supportsModelRoutingV1: capabilities.modelRoutingV1, @@ -829,6 +834,7 @@ function capabilitiesEqual( a.miniAppAgentContextFilesV1 === b.miniAppAgentContextFilesV1 && a.miniAppAgentImagesV1 === b.miniAppAgentImagesV1 && a.wslWorkspacesV1 === b.wslWorkspacesV1 && + a.sshNoneAuthV1 === b.sshNoneAuthV1 && a.sshPortScopedIdentityV1 === b.sshPortScopedIdentityV1 && a.subscriptionAccountPoolsV1 === b.subscriptionAccountPoolsV1 && a.subscriptionQuotaV1 === b.subscriptionQuotaV1 && diff --git a/src/web-ui/src/infrastructure/peer-device/README.md b/src/web-ui/src/infrastructure/peer-device/README.md index a70d675966..b0e2f10bcc 100644 --- a/src/web-ui/src/infrastructure/peer-device/README.md +++ b/src/web-ui/src/infrastructure/peer-device/README.md @@ -276,6 +276,9 @@ listener alone recovers an interaction emitted before attachment. before RPC. Missing capability means unsupported, including older Desktop and CLI peers. Discovery reports the host's OS availability; it must never inspect or execute the controller's WSL installation as a fallback. + `ssh_none_auth_v1` gates SSH profile requests with `auth.type === 'None'` + the same way; an older host cannot parse that method, so controllers reject + the request before RPC and keep the record unchanged. 19. **Session copying needs an explicitly negotiated request contract.** `whole_session_copy_v1` enables the dedicated `copy_session` command. diff --git a/src/web-ui/src/infrastructure/peer-device/peerCapabilityResolution.test.ts b/src/web-ui/src/infrastructure/peer-device/peerCapabilityResolution.test.ts index 4749c1ad0c..c23f18262b 100644 --- a/src/web-ui/src/infrastructure/peer-device/peerCapabilityResolution.test.ts +++ b/src/web-ui/src/infrastructure/peer-device/peerCapabilityResolution.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'; import { canCopySessionsOnSurface, + canUseSshNoneAuthOnSurface, canViewPullRequestsOnSurface, canQueryToolCatalogOnSurface, canSubmitUserQuestionsOnSurface, @@ -51,6 +52,15 @@ it('requires explicit host allowance-query capability and never falls back to co expect(canQuerySubscriptionQuotaOnSurface(true, caps({ subscriptionQuotaV1: true }))).toBe(true); }); +describe('canUseSshNoneAuthOnSurface', () => { + it('requires the negotiated capability on a peer surface', () => { + expect(canUseSshNoneAuthOnSurface(false, null)).toBe(true); + expect(canUseSshNoneAuthOnSurface(true, null)).toBe(false); + expect(canUseSshNoneAuthOnSurface(true, { sshNoneAuthV1: false } as PeerHostCapabilities)).toBe(false); + expect(canUseSshNoneAuthOnSurface(true, { sshNoneAuthV1: true } as PeerHostCapabilities)).toBe(true); + }); +}); + describe('canCopySessionsOnSurface', () => { it('requires explicit peer support even for older Desktop hosts', () => { expect(canCopySessionsOnSurface(false, null)).toBe(true); diff --git a/src/web-ui/src/infrastructure/peer-device/peerCapabilityResolution.ts b/src/web-ui/src/infrastructure/peer-device/peerCapabilityResolution.ts index a47225f922..4f2dcae2c7 100644 --- a/src/web-ui/src/infrastructure/peer-device/peerCapabilityResolution.ts +++ b/src/web-ui/src/infrastructure/peer-device/peerCapabilityResolution.ts @@ -26,6 +26,14 @@ export function canCopySessionsOnSurface( return !peerActive || capabilities?.wholeSessionCopyV1 === true; } +/** A host without the key cannot parse `None`; only the local surface is implicit. */ +export function canUseSshNoneAuthOnSurface( + peerActive: boolean, + capabilities: PeerHostCapabilities | null, +): boolean { + return !peerActive || capabilities?.sshNoneAuthV1 === true; +} + /** * Resolve whether the currently rendered surface can be queried for the * read-only tool catalog (`get_all_tools_info`), so the UI skips the invoke diff --git a/src/web-ui/src/locales/en-US/common.json b/src/web-ui/src/locales/en-US/common.json index ffa7b59a1c..597cb3f776 100644 --- a/src/web-ui/src/locales/en-US/common.json +++ b/src/web-ui/src/locales/en-US/common.json @@ -1991,6 +1991,9 @@ "privateKey": "Private Key", "sshAgent": "SSH Agent", "keyboardInteractive": "Keyboard-interactive", + "noAuth": "No authentication", + "noAuthHint": "The server accepts the connection without credentials. Use this for tunnels that are already authenticated, such as a Coder workspace agent.", + "noAuthUnsupported": "This host must be updated before it can connect without authentication.", "privateKeyPath": "Private Key File Path", "certificatePath": "OpenSSH certificate", "certificatePathOptional": "Optional certificate file", diff --git a/src/web-ui/src/locales/zh-CN/common.json b/src/web-ui/src/locales/zh-CN/common.json index 936d8dc716..c8ba9d855a 100644 --- a/src/web-ui/src/locales/zh-CN/common.json +++ b/src/web-ui/src/locales/zh-CN/common.json @@ -1991,6 +1991,9 @@ "privateKey": "私钥", "sshAgent": "SSH 密钥代理", "keyboardInteractive": "键盘交互认证", + "noAuth": "无认证", + "noAuthHint": "服务器不校验凭据,适用于已完成认证的隧道,例如 Coder 工作区 agent。", + "noAuthUnsupported": "此主机需要更新后才能使用无认证连接。", "privateKeyPath": "私钥文件路径", "certificatePath": "OpenSSH 证书", "certificatePathOptional": "可选证书文件", diff --git a/src/web-ui/src/locales/zh-TW/common.json b/src/web-ui/src/locales/zh-TW/common.json index e18bd0f45b..08e48d5dcf 100644 --- a/src/web-ui/src/locales/zh-TW/common.json +++ b/src/web-ui/src/locales/zh-TW/common.json @@ -1991,6 +1991,9 @@ "privateKey": "私鑰", "sshAgent": "SSH 金鑰代理", "keyboardInteractive": "鍵盤互動驗證", + "noAuth": "不驗證", + "noAuthHint": "伺服器不驗證憑證,適用於已完成驗證的通道,例如 Coder 工作區 agent。", + "noAuthUnsupported": "此主機需要更新後才能使用不驗證連線。", "privateKeyPath": "私鑰檔案路徑", "certificatePath": "OpenSSH 憑證", "certificatePathOptional": "可選憑證檔案",